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

Time:11-09

The scenario (JAVA/UNIX):

Process A writes a File to Disk (using FileOutputStream)

Process B tries to read the same File while Process A is still writing (using FileInputStream)

questions:

  • will Process A be able to successfully write the file to disk, even if Process B tries to read?
  • what happens in Process B ? is the file locked? is there an IOException thrown? or can it read the incomplete file?

CodePudding user response:

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

Yes. It will be able to write the file correctly. Reads do not interfere with a write ... on Linux.

  1. What happens in Process B ? is the file locked? is there an IOException thrown? or can it read the incomplete file?

It will probably see an incomplete file. (It might see a complete file ... if you are lucky.)

Linux doesn't lock files by default. To get locking, both the reader and the writer need to make flock(2) syscalls. In Java that maps to using FileLock.

No Java IOException will be thrown on UNIX / Linux / MacOS. (Or on Android.) You will only run into locking issues on Windows.


Any hints appreciated.

Hint: you could just write a little test program and try it ....

  • Related