FileInputStream and FileOutputStream to the same file: Is read () guaranteed to see all records () s that were "before"?

I use the file as a cache for big data. One thread writes to it sequentially, another thread reads it sequentially.

Can I be sure that all the data that was written (using the write() method in one stream can be read() from another stream, provided that the “occurs before” relationship is correct from the point of view of the Java memory model? Is this behavior documented?

In my JDK, FileOutputStream does not override flush() , and OutputStream.flush() empty. That's why I wonder ...

The threads in question belong exclusively to a class that I have full control over. Each thread is guaranteed to be available only to one thread. My tests show that this works as expected, but I'm still wondering if this is guaranteed and whether this is documented.

See also this related discussion .

+8
source share
4 answers

If you are using the posix file system, then yes.

FileInputStream and FileOutputStream on * nix use the read and write system calls for internal purposes. The documentation for the record says that reads will see the results of past records ,

After writing () to the regular file successfully returned:

Any successful read () from each byte position in a file that has been modified by this record should return the data specified by write () for that position until such byte positions are changed again.

I am pretty sure that ntfs on Windows will have the same read() write() guarantees.

+9
source

You cannot talk about the happen-to relationship in terms of the Java memory model between your FileInputStream and FileOutputStream , since they do not share memory or stream. VM freely reorders them only according to your synchronization requirements. If you have the correct synchronization between reading and writing without application level buffering, you are safe.

However, FileInputStream and FileOutputStream share a file that leaves things up to the OS that you can expect in the main stream after recording in order.

+3
source

No, you need to flush () the streams (at least for buffering streams (Input | Output)), otherwise you might have data in the buffer.

Perhaps you need a parallel data structure structure ?

0
source

If FileOutputStream does not override flush (), I think you can be sure that all the data written by write () can be read by read () if your OS does not do something strange with the data (for example, it starts a new stream, which expects the hard drive to spin at the right speed instead of locking, etc.) so that it is not recorded immediately.

0
source

All Articles