FileInputStream and FileOutputStream to the same file: Is a read() guaranteed to see all write()s that “happened before”?

无人久伴 提交于 2020-01-19 11:16:40

问题


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

Can I be sure that all data that has been written (by write()) in one thread can be read() from another thread, assuming a proper "happens-before" relationship in terms of the Java memory model? Is this behavior documented?

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

The streams in question are owned exclusively by a class that I have full control of. Each stream is guaranteed to be accesses by one thread only. My tests show that it works as expected, but I'm still wondering if this is guaranteed and documented.

See also this related discussion.


回答1:


Assuming you are using a posix file system, then yes.

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

After a write() to a regular file has successfully returned:

Any successful read() from each byte position in the file that was modified by that write shall return the data specified by the write() for that position until such byte positions are again modified.

I'm pretty sure ntfs on windows will have the same read() write() guarantees.




回答2:


You can't talk about "happens-before" relationship in terms of the Java memory model between your FileInputStream and FileOutputStream objects since they don't share any memory or thread. VM is free to reorder them just honoring your synchronization requirements. When you have proper synchronization between reads and writes without application level buffering, you are safe.

However FileInputStream and FileOutputStream share a file, which leaves things up to the OS which in main stream ones you can expect to read after write in order.




回答3:


No, you need to flush() the Streams (at least for Buffered(Input|Output)Streams), otherwise you could have data in a buffer.

Maybe you need a concurrent data structure?




回答4:


If FileOutputStream does not override flush(), then I think you can be sure all data written by write() can be read by read(), unless your OS does something weird with the data (like starting a new thread that waits for the hard drive to spin at the right speed instead of blocking, etc) so that it is not written immediately.



来源:https://stackoverflow.com/questions/12741937/fileinputstream-and-fileoutputstream-to-the-same-file-is-a-read-guaranteed-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!