java - 我需要 FileDescriptor "sync"和 MappedByteBuffer "force"吗?

标签 java nio memory-mapped-files

当我想确保 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/

相关文章:

java - json 解析新手 - 如何获取数组中的数组

java - 在新线程中创建 JFrame(new messageloog)

java - 如何从字节缓冲区打印字符串

Java - 如何将 Files.lines() 的 URL 转换为 PATH

java - FileChannel 和 RandomAccessFile 似乎不起作用

java - 如何在 Java 中修复 'SQLRecoverableException: Closed Connection'

java - Java 中对 MacOS X 的 native Swing 菜单栏支持

c++ - boost 内存映射文件是否在 Linux 上归零

windows - 使用内存映射文件同时允许其他进程完全访问

java - 我应该为我的简单流程使用内存映射文件吗?