Java file lock for read and write with multiple processes

843 views Asked by At

In my application multiple processes are trying access a file for read and write. Every application has a single thread. I need to make sure that no 2 processes are accessing the file at the same time. I am using FileLock in JDK. This works fine, when one process has acquired the lock and other process tries to access to the file (for read or write) exception is thrown stating file has been locked by other process.

Now i need to make sure that, for 2nd process rather then throwing the exception thread should wait till lock is released by first process and once lock is released continue with its work.

How can I do this. So, fat I have not been able it figure out someway of doing this.

1

There are 1 answers

3
shakhawat On

Have you considered implementing something like below?

while (true) {
   try to acquire lock - {
     // if the lock is acquired break the loop     

   } catch (Exception) {
     log... exception
     possibly wait for sometime
  }
}