10

In https://stackoverflow.com/questions/730521/really-force-file-sync-flush-in-java, the author writes in the summary of the answers:

Use c.force(true) followed by s.getFD().sync() for Java NIO

My question is: do you really need both? Isn't force enough? Aren't force and sync just different interfaces for doing the same thing? I can't find anyplace where this is confirmed.

1
  • Currently, both implementations call the native function fsync() (or fdatasync() in case of FileChannel.force with false). I've found them in src/java.base/unix/native/libnio/ch/UnixFileDispatcherImpl.c (FileChannel native end call) and src/java.base/unix/native/libjava/FileDescriptor_md.c (FileDescriptor native implementation) - OpenJDK's commit id ee57e731d03
    – Luciano
    Commented Nov 3, 2023 at 14:29

1 Answer 1

13

My understanding is that the correct answer is No.

FileChannel.force calls fdatasync or fsync. This can be seen in jdk/src/solaris/native/sun/nio/ch/FileChannelImpl.c on of the OpenJDK source code. FileDescriptor calls fsync (To find this out was more complex. I finally traced it to jvm.cpp).

I am the "author" of the linked question. So I was wrong. What is NOT enough is FileOutputStream.flush. because it is a no-op. You therefore either need force or sync.

Not the answer you're looking for? Browse other questions tagged or ask your own question.