Search code examples
javaclinuxmmapmemory-mapped-files

Do we have to flush MappedByteBuffer when underlying channel is opened with StandardOpenOption.SYNC


Does StandardOpenOption.SYNC work with MappedByteBuffers and save us calling MappedByteBuffer.force()?

Set<OpenOption> options = new HashSet<>();
options.add(StandardOpenOption.READ);
options.add(StandardOpenOption.WRITE);
options.add(StandardOpenOption.CREATE);
options.add(StandardOpenOption.SYNC);

FileChannel channel = FileChannel.open("file.tmp", options);
MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_WRITE, 0,  channel.size());

buf.putInt(500);
buf.force(); // Needed or not?

Edit :

I assume jdk uses O_SYNC flag and mmap() call, so extending this question to linux world : Do we have to call msync() when underlying fd is opened with O_SYNC flag ?


Solution

  • I can't find a document to verify it.

    Tested on linux/windows with and without SYNC option, performance was similar, so I assume file option SYNC/O_SYNC does not apply to mmap/MappedByteBuffer operations.