为什么我会收到“太多打开的文件”错误? [英] Why do I get "Too many open files" errors?

查看:231
本文介绍了为什么我会收到“太多打开的文件”错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己不得不在我的Groovy脚本中显式调用System.gc(),以防止类似下面的错误。垃圾收集器为什么不为我做这个?有什么我可以做它导致它垃圾收集,以防止这些错误(也许JAVA_OPTS)?

I find myself having to explicitly call System.gc() in my Groovy scripts to prevent errors like the one below. Why doesn't the garbage collector do this for me? Is there something I can do to cause it to garbage collect to prevent these errors (maybe JAVA_OPTS)?

Caught: java.util.concurrent.ExecutionException: org.codehaus.groovy.runtime.InvokerInvocationException: java.io.IOException: Cannot run program "ls": java.io.IOException: error=24, Too many open files
    at groovyx.gpars.GParsPool.runForkJoin(GParsPool.groovy:305)
    at UsageAnalyzer$_run_closure2_closure6.doCall(UsageAnalyzer.groovy:36)
    at groovyx.gpars.GParsPool$_withExistingPool_closure1.doCall(GParsPool.groovy:170)
    at groovyx.gpars.GParsPool$_withExistingPool_closure1.doCall(GParsPool.groovy)
    at groovyx.gpars.GParsPool.withExistingPool(GParsPool.groovy:169)
    at groovyx.gpars.GParsPool.withPool(GParsPool.groovy:141)
    at groovyx.gpars.GParsPool.withPool(GParsPool.groovy:117)
    at groovyx.gpars.GParsPool.withPool(GParsPool.groovy:96)
    at UsageAnalyzer$_run_closure2.doCall(<removed>)
    at UsageAnalyzer.run(<removed>)

程序,但它也发生在顺序程序中。

This stack trace is from a parallel program but it happens in sequential programs as well.

推荐答案

在使用groovy时,可以使用方便的方法,如 File.withReader() File.withWriter() File.withInputStream / code>, InputStream.withStream()确保资源完全关闭。这不像使用Java的 try .. finally idiom那样麻烦,因为不需要显式地调用 close(),或者在 try 块之外声明一个变量。

As you're using groovy, you can use the convenient methods such as File.withReader(), File.withWriter(), File.withInputStream(), InputStream.withStream() to ensure resources get closed cleanly. This is less cumbersome than using Java's try .. finally idiom, as there's not need to explicitly call close(), or declare a variable outside the try block.

例如

File f = new File('/mumble/mumble/')
f.withReader{ r -> 
   // do stuff with reader here
}

这篇关于为什么我会收到“太多打开的文件”错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆