Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I/O concept flush vs sync

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

like image 414
smartnut007 Avatar asked Nov 01 '10 20:11

smartnut007


People also ask

Does Fflush call Fsync?

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() .

What does flushing a file mean?

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.


1 Answers

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:

  • http://download.oracle.com/javase/6/docs/api/java/io/OutputStream.html#flush%28%29
  • http://download.oracle.com/javase/6/docs/api/java/io/Writer.html#flush%28%29
  • http://download.oracle.com/javase/6/docs/api/java/io/FileDescriptor.html#sync%28%29
  • http://linux.die.net/man/2/sync
like image 85
Grodriguez Avatar answered Oct 05 '22 23:10

Grodriguez