I/O concept flush vs sync

后端 未结 1 604
情书的邮戳
情书的邮戳 2020-11-28 04:13

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

相关标签:
1条回答
  • 2020-11-28 05:10

    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
    0 讨论(0)
提交回复
热议问题