• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

fflush and fsync

 
Raees Uzhunnan
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Should we use fflush and fsync on java at all. if so how .. in other terms how do we make sure a java write is definitely written into the disk and not into the I/O buffer ?

in C and C++ we get the two APIs fflush and fsync for the same purpose

Thanks
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you're asking if Java has an equivalent to C's fflush and fsync. There are no methods called either fflush or fsync in Java. But if you're using a Writer or a Stream (e.g. a FileWriter or FileOutputStream) then you should call flush() to ensure that everything in the buffers has been written to disk. Calling close() also accomplishes this (so you really only need flush() if you want to keep the stream open afterwards for some reason). For writers and outputstreams, there is no need for fsync or any equivalent; it's all handled by flush() or close(). If you're using a RandomAccessFile you need to call close() at the end to achieve the effect of a fflush and fsync, and if you're using a FileChannel you can call either close() or force() - the latter allows the channel to remain open, like flush(). For other classes, just look at the API and see what options they offer. Some sort of close() operation is most common in Java.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In fact, in both RandomAccessFile and FileOutputStream, you can call getFD() to get the FileDescriptor. This has a method sync(), which you can call, to ensure that the OS flushes all buffers. That is not the same as flushing a Java stream.

I don't know how worthwhile or necessary it is to call this method, but it does exist.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah yes, I forgot about that. It would be nice to know if there are circumstances where close() is not enough, where you really need to do a getFD().sync() before closing. That seems an absurdly poor design if so, hiding a vital function in a separate class. It might account for some bad behavior I've seen on a few filesystems though. How annoying.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic