我正在使用一个文件作为大数据的缓存。一个线程顺序写入它,另一个线程顺序读取它。
我能否确定在一个线程中(通过write()
)写入的所有数据都可以从另一个线程中被read()
,假设适当的“在 Java 内存模型方面发生“之前”的关系?这种行为是否记录在案?
在我的JDK中,FileOutputStream
没有覆盖flush()
,OutputStream.flush()
是空的。这就是为什么我想知道...
有问题的流完全由我完全控制的类拥有。每个流都保证只能由一个线程访问。我的测试表明它按预期工作,但我仍然想知道这是否得到保证和记录。
最佳答案
假设您使用的是 posix 文件系统,那么可以。
*nix 上的FileInputStream
和 FileOutputStream
在内部使用读写系统调用。 write 的文档说 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.
我很确定 Windows 上的 ntfs 将具有相同的 read()
write()
保证。
关于java - FileInputStream 和 FileOutputStream 到同一个文件 : Is a read() guaranteed to see all write()s that "happened before"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12741937/