我正在使用 MappedByteBuffer 来加速文件读/写操作()。我的问题如下:
我不确定是否需要使用 .force() 方法将内容刷新到磁盘。似乎没有 .force(),.getInt() 仍然可以完美地工作(好吧,因为这是一个内存映射缓冲区,我假设 .getInt() 从磁盘获取数据,这意味着数据已经被刷新到磁盘已经。
.force() 方法是阻塞方法吗?
阻塞方法是同步块(synchronized block)吗?
调用或不调用 .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)课主要{
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");
}
最佳答案
只有在您有极端的交易要求时才应调用它,即您正在实现数据库。 getInt() 从内存中读取:操作系统将文件分页进出该内存。
未指定。
如果指定,方法是同步的。跟封不封没关系。
参见 (1)。数据仍将被写入,但由操作系统决定,而不是您的决定。
我对此表示怀疑,但请参阅 (2),并且我怀疑您根本不需要调用它,请参阅 (1)。
关于java - 我们是否需要使用 MappedByteBuffer.force() 将数据刷新到磁盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4096881/