2

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.

Jin. K
  • 141
  • 2
  • 10
  • FWIW FileChannel#lock is to lock out *other processes* not to synchronize between threads of the same JVM: http://stackoverflow.com/questions/128038/how-can-i-lock-a-file-using-java-if-possible – Thilo Jul 23 '12 at 05:25
  • Thanks to your reference. So.. FileChannel.lock() is only valid among processes not threads? and I really have to use synchronizing approach... right? – Jin. K Jul 23 '12 at 05:37

1 Answers1

1

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.

Joe M
  • 2,527
  • 1
  • 25
  • 25
  • Synchronized block on the method is not my option like you mentioned. File reading/writing is major job on my app. If each thread is accessing different files, they don't need to be synchronized. I hope write() method blocked when file is opened with least additional code. if it's not possible i will have to determine whether a file is accessed by different thread by my self (string match...etc) – Jin. K Jul 23 '12 at 05:21
  • You could have the synchronized block use some object representing the file as a lock. Doesn't have to be global. – Thilo Jul 23 '12 at 05:24