我使用MappedByteBuffer來加速文件的讀/寫操作()。我的問題如下:我們是否需要使用MappedByteBuffer.force()將數據刷新到磁盤?
我不知道我是否需要使用.force()方法來刷新內容磁盤。看起來像沒有.force(),.getInt()仍然可以完美工作(當然,因爲這是一個內存映射緩衝區,我假設.getInt()從磁盤獲取數據,這意味着數據已被刷新到磁盤了。
是在.force()方法的阻塞方法?
是一個阻塞方法的synchronized塊?
有使用或不調用.force(巨大的性能差異)方法手動調用.force()的好處是什麼?我們應該在哪種情況下使用它?我假設不調用它,數據仍然會被寫到磁盤後面的場景中
如果我們需要調用.force(),將從另一個線程調用它有助於提高性能?由於同步問題會損壞數據嗎?
import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode;
公共類主要{
public static void main(String[] args) throws IOException {
System.out.println("start");
RandomAccessFile raf = new RandomAccessFile("test.map", "rw");
FileChannel fc = raf.getChannel();
MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, 0, 2000000);
int total = 0;
long startTime = System.currentTimeMillis();
for (int i = 0; i < 2000000; i += 4) {
mbb.putInt(i, i);
//mbb.force();
total += mbb.getInt(i);
}
long stopTime = System.currentTimeMillis();
System.out.println(total);
System.out.println(stopTime - startTime);
System.out.println("stop");
}
}
JDK的版本? (並不是說它真的發生了很大的變化) – 2010-11-04 13:06:05
我沒有看到會有什麼不同。 – EJP 2010-11-04 13:10:20
在查看Javadoc後無:-) – 2010-11-04 13:39:52