I have come across these two terms and my understanding of them seem to overlap with each other. Flush is used with buffers and sync is used to talk about persisting changes of file to disk.
In C, fflush(stdin) makes sure that the buffer is cleared. And fsync to persist changes file to disk.
If these concepts are not universally defined, would prefer a linux, java explanation.
I found a related post, but ir doesn't really answer my question. Really force file sync/flush in Java
You would need to both call fflush() and fsync() , yes. In general people that care about that do not use buffered I/O (using setvbuf() for example) so they usually just do a fsync() .
Typically this means that the data will be copied from the program buffer to the operating system buffer. Specifically what this means is that if another process has that same file open for reading, it will be able to access the data you just flushed to the file.
In Java, the flush()
method is used in output streams and writers to ensure that buffered data is written out. However, according to the Javadocs:
If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive.
On the other hand, FileDescriptor.sync()
can be used to ensure that data buffered by the OS is written to the physical device (disk). This is the same as the sync
call in Linux / POSIX.
If your Java application really needs to ensure that data is physically written to disk, you may need to flush
and sync
, e.g.:
FileOutputStream out = new FileOutputStream(filename); [...] out.flush(); out.getFD().sync();
References:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With