当我想确保 MappedByteBuffer 的更改应同步回光盘时,我需要 randomAcccessFile.getFD().sync()
或 mappedByteBuffer.force()
或两者兼而有之? (在我的简单测试中,似乎没有一个是必需的 - 令人困惑......)
有人了解实际的底层操作,或者至少可以解释其中的差异(如果有的话)?
最佳答案
首先,FileDescriptor.sync相当于FileChannel.force(调用POSIX fsync方法)
其次,在 Ron Hitchens 的书“Java NIO”(来自 google books)中关于 MappedByteBuffer 的章节中提到
MappedByteBuffer.force() is similar to the method of the same name in the FileChannel class. It forces any changes made to the mapped buffer to be flushed out to permanent disc storage. When updating a file through MappedByteBuffer object, you should always use MappedByteBuffer.force() rather than FileChannel.force(). The channel object may not be aware of all file updates made through the mapped buffer. MappedByteBuffer doesn't give you the option of not flushing file metadata - it's always flushed too. Note, that the same considerations regarding nonlocal filesystems apply here as they do for FileChannel.force
所以,是的。您需要调用 MappedByteBuffer.force!
但是后来我发现this bug这表明至少在 Windows 上这两个调用仍然是必要的。
关于java - 我需要 FileDescriptor "sync"和 MappedByteBuffer "force"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14011398/