Java/Unix: 如果另一个进程试图在其间读取文件,进程能否成功写入文件

Java/Unix: Can a Process sucessfully write a File if another Process tries to reads it inbetween

场景(JAVA/UNIX):

进程 A 将文件写入磁盘(使用 FileOutputStream)

进程 B 尝试读取同一个文件,而进程 A 仍在写入(使用 FileInputStream)

问题:

  1. Will Process A be able to successfully write the file to disk, even if Process B tries to read?

是的。它将能够正确写入文件。在 Linux.

上读取不会干扰写入 ...
  1. What happens in Process B ? is the file locked? is there an IOException thrown? or can it read the incomplete file?

它可能会看到一个不完整的文件。 (它可能会看到一个完整的文件......如果你幸运的话。)

Linux 默认不锁定文件。要获得锁定,reader 和编写器都需要进行 flock(2) 系统调用。在 Java 中映射到使用 FileLock.

不会在 UNIX / Linux / MacOS 上抛出 Java IOException。 (或 Android。)你只会 运行 进入 Windows 的锁定问题。


Any hints appreciated.

提示:您可以编写一个小测试程序并尝试一下....