我正在使用 MappedByteBuffer 来加速文件读/写操作()。我的问题如下:
我不确定是否需要使用 .force() 方法将内容刷新到磁盘。似乎没有 .force(),.getInt() 仍然可以完美工作(好吧,因为这是一个内存映射缓冲区,我假设 .getInt() 从磁盘获取数据,这意味着数据已被刷新到磁盘已经。
.force() 方法是阻塞方法吗?
阻塞方法是同步块吗?
调用或不调用 .force() 方法存在巨大的性能差异。手动调用 .force() 有什么好处?我们应该在什么情况下使用它?我假设不调用它,数据仍将在后台写入磁盘。
如果我们需要调用 .force(),从另一个线程调用它是否有助于提高性能?它会因为同步问题而损坏数据吗?
导入 java.io.FileNotFoundException;导入 java.io.IOException;导入 java.io.RandomAccessFile;导入 java.nio.MappedByteBuffer;导入 java.nio.channels.FileChannel;导入 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");
}
}