在我的程序中,关闭 java.util.RandomAccessFile 有时需要恰好 45 秒(好吧,几乎恰好:在 44.998 到 45.003 秒之间)。该程序创建并关闭了许多小文件。通常关闭文件非常快(在 0 到 0.1 秒之间)。如果我调试程序,它会卡在 native 方法 RandomAccessFile.close0 中。
使用FileOutputStream而不是RandomAccessFile时也会出现同样的问题(此时程序被阻塞在本地方法FileOutputStream.close0)。
有人知道那是什么吗?你能在你的系统上重现这个问题吗(我只能在 Mac 上重现,不能在 Windows XP 上重现;我还没有在 Linux 上测试过)?
更新 2:
这似乎只发生在 Mac OS X 上。我使用 JDK 1.6.0_22-b04。它发生在 32 位和 64 位上。在 Windows XP 上似乎不会发生。
我的测试用例是:
import java.io.File;
import java.io.RandomAccessFile;
public class TestFileClose {
public static void main(String... args) throws Exception {
for (int i = 0; i < 100000; i++) {
String name = "test" + i;
RandomAccessFile r = new RandomAccessFile(name, "rw");
r.write(0);
long t = System.currentTimeMillis();
r.close();
long close = System.currentTimeMillis() - t;
if (close > 200) {
System.out.println("closing " + name +
" took " + close + " ms!");
}
if (i % 2000 == 0) {
System.out.println("test " + i + "/100000");
}
new File(name).delete();
}
}
}
我机器上的示例输出:
test 0/100000
test 2000/100000
test 4000/100000
test 6000/100000
test 8000/100000
test 10000/100000
closing test10030 took 44998 ms!
test 12000/100000
test 14000/100000
test 16000/100000
closing test16930 took 44998 ms!
test 18000/100000
test 20000/100000
最佳答案
就我而言,结果是我的机器上安装了 McAfee 防病毒软件。我必须安装它(公司政策)...
如果我禁用按访问扫描,问题也会出现。
关于java - 关闭 RandomAccessFile 有时恰好需要 45 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4760809/