问题描述
我正在使用MappedByteBuffer来加速文件读/写操作()。我的问题如下:
I am using MappedByteBuffer to speed up file read/write operations(). My questions as below:
-
我不确定是否需要使用.force()方法将内容刷新到磁盘或不。似乎没有.force(),.getInt()仍然可以正常工作(好吧,因为这是一个内存映射缓冲区,我假设.getInt()从磁盘中获取数据,这意味着数据已被刷新到磁盘已经。
I am not sure if I need to use .force() method to flush the content to disk or not. It seems like without .force(), the .getInt() can still work perfectly (well, since this is a memory-mapped buffer, i assume .getInt() fetches the data from disk, which means the data has been flushed into disk already.
.force()方法是阻塞方法吗?
Is the .force() method a blocking method?
阻塞方法是一个同步块吗?
Is a blocking method a synchronized block?
无论是否调用.force()方法都存在巨大的性能差异。调用.force(有什么好处) )手动?在哪种情况下我们应该使用它?我假设没有调用它,数据仍将被写入现场后面的磁盘。
There is a huge performance difference with or without calling .force() method. What's the benefit of calling .force() manually? Under which situation should we use it? I assume without calling it, the data will still be written to disk behind the scene.
如果我们需要调用.force(),从另一个线程调用它有助于提高性能吗?它会因为同步问题而破坏数据吗?
If we needs to call .force(), will calling it from another thread helps to improve performace? Will it corrupt the data because of synchronization problem?
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.F ileChannel;
import java.nio.channels.FileChannel.MapMode;
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 class Main {
public class Main {
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()从内存中读取:操作系统将文件分页进出内存。
You should call it only if you have extreme transactional requirements, i.e. you are implementing a database. getInt() reads from memory: the operating system pages the file into and out of that memory.
未指定。
如果指定了方法,则会同步方法。它与是否阻止无关。
Methods are synchronized if so specified. It has nothing to do with whether they block or not.
见(1)。数据仍将被写入,但是在操作系统的心血来潮而不是你的。
See (1). Data will still be written but at the operating system's whim rather than yours.
我对此表示怀疑,但请看(2),我怀疑你需要完全叫它,见(1)。
I doubt it, but see (2), and I doubt that you need to call it at all, see (1).
这篇关于我们是否需要使用MappedByteBuffer.force()将数据刷新到磁盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!