Search code examples
javafileconcurrencyblocking

Java accessing a file among threads at the same time


I have some confusions on java file lock.

here's my situation.

  1. Each thread can read/write a file.
  2. My file manipulating method can be called by several threads at the same time

and, my goal is clear, no concurrent write to a file by threads. Always one thread allowed to write a file.

My questions are

  1. If FileOutputStream.write() was thread safe, I didn't have to put any concurrency mechanism in my code since the code at the write() will block until a locked file will be released. However, my program would not seem to block when a file is opened by a thread (i am not sure for this)

  2. If FileOutputStream.write() was NOT thread safe, I would have to write additional code to make a file accessed by only thread at a time. Therefore, I used FileChannel.lock() to do so. However, different from the JDK document it does not block but throw an OverlappingFileLockException.

I would appreciate your clear advise.


Solution

  • It is not thread safe and you need to programmatically ensure safety. Just put the relevant code in a synchronized block assuming there is no major performance requirement for your app.