-1

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.

Bagira
  • 2,149
  • 4
  • 26
  • 55

1 Answers1

0

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
  }
}
shakhawat
  • 2,639
  • 1
  • 20
  • 36
  • May be, because of pseudo code or while (true) – rpc1 Mar 16 '20 at 08:31
  • How do you expect this code to work in case of multiple processes when both are trying to acquire lock on same file? – Bagira Mar 16 '20 at 08:38
  • Both will keep looping and eventually one of them will be able to acquire the lock. If the acquiring lock implementation is not thread-safe, you have to keep that in a sync block to make thread-safe – shakhawat Mar 16 '20 at 08:47