suppose I have a file that might gets written by one thread/process Writer and read by another thread/process Reader.
Writer updates the file every x time interval, and Reader reads it every y time interval,
if they happen to read and write to the file at the same time, will there be any issues? would the read block until writes finishes? or would the read fails? and vice versa?
What’s the best practice here?
suppose I have a file that might gets written by one thread/process Writer and
Share
You’ll need to devise your own locking protocol to implement in the applications. Specifics depend on the underlying operating system, but in general, nothing will stop one process from reading a file even when another process is writing to it.
Java has a
FileLockclass that can be used to coordinate access to a file. However, you’ll need to read the caveats carefully, especially those relating to the system-dependence of this feature. Testing the feature on the target operating system is extremely important.A key concept of Java’s
FileLockis that it is only “advisory”. Your process should be able to detect that another process holds a lock on a file, but your process can ignore it and do what it likes with the file, no restrictions.The question is ambiguous whether multiple process will use the file, or merely separate threads within a single Java process. That’s a big difference. If the problem requires only thread safety within a single process, a
ReentrantReadWriteLockcan provide a robust, high performance solution, without any platform-specific pitfalls.