【发布时间】:2014-08-13 06:07:56
【问题描述】:
不确定我的代码的哪一部分确切导致了问题,但是当我开始查明问题时,我注意到当我运行以下代码时打开的文件数会增加。
public synchronized String readStringSync(String basePath,String path){
if(useLegacy){
return readStringLegacy(basePath,path);
}
if(!basePath.endsWith("/"))
basePath+="/";
StringBuffer sb = new StringBuffer(420);
File f= new File(basePath+path);
if(!f.exists()){
return null;
}
Charset charset = Charset.forName("UTF-8");
try (BufferedReader reader = Files.newBufferedReader(Paths.get(f.getAbsolutePath()), charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line+"\r\n");
}
String ret = sb.toString();
if(ret.trim().startsWith("deleted")||ret.trim().equalsIgnoreCase("dummy"))
return null;
return ret;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static void main(String... args) throws Exception{
com.sun.management.UnixOperatingSystemMXBean mxb = (com.sun.management.UnixOperatingSystemMXBean)java.lang.management.ManagementFactory.getOperatingSystemMXBean();
System.out.println(mxb.getOpenFileDescriptorCount()); //11
System.out.println(readString("sometestfile"));
Thread.sleep(1000);
mxb = (com.sun.management.UnixOperatingSystemMXBean)java.lang.management.ManagementFactory.getOperatingSystemMXBean();
System.out.println(mxb.getOpenFileDescriptorCount()); //12 wtf
}
我已经尝试摆脱 File.exists 并用 Files.exists 替换它,但这完全没有任何效果。
由于stackoverflow仍在抱怨缺少细节,这是我正在使用的java版本:
java版本“1.7.0_51” OpenJDK 运行时环境 (IcedTea 2.4.4) (7u51-2.4.4-0ubuntu0.13.04.2) OpenJDK 64 位服务器虚拟机(build 24.45-b08,混合模式)
【问题讨论】:
-
useLegacy的值是多少?问题可能在readStringLegacy()内部。 -
尝试添加 if(true)return null;就在 try 块 => 文件计数保持在 11 之前,所以它是关于 try 块所做的事情的定义
-
编写一个
for循环,迭代次数大约为 1000 次,并在其中调用相同的readStringSync()以读取相同的文件。打印之后打开的文件数。 -
尝试将等待时间设置为 10 秒 + 以 System.gc() 开头,没有效果
-
icza,还有 12 个打开的文件