在我的程序中,关闭一个 java.util.RandomAccessFile 有时需要 45 秒(嗯,几乎完全是:44.998 到 45.003 秒之间)。该程序创建并关闭许多小文件。通常关闭文件非常快(在 0 到 0.1 秒之间)。如果我调试程序,它会卡在本机方法 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