-1

I have many threads which monitor a certain state. If the application gets into that state, then I need to do some extra work. I want to allow just 1 thread to execute that and want to block the others until that work is finished. Blocking mean, that they must not execute that task again.

I have the following scenario:

    ReentrantLock lock = new ReentrantLock

    void doSomething() {

      if (lock.tryLock()) {

       try {
         doSomeWork()
       } finally {
         lock.unLock()
       }
      } else {
        // wait for DoSomeWork is done
      }
    }

I can monitor lock.isLocked() in a loop, but actually I just want to have some sort of wait until the work is finished by the other thread.

HamoriZ
  • 2,370
  • 18
  • 38
  • What exactly is your issue? You can use `lock.lock()` which will wait for the lock to be released and guaratees that only one thread has it at a given time, isn't that what you want? – daniu Sep 06 '19 at 09:13
  • ah yes, somehow I just overcomplicated it. having `try {lock.lock() } finally {lock.unlock()}` will solve the problem – HamoriZ Sep 06 '19 at 09:34

1 Answers1

0

According to documentation about ReentrantLock class:

It is recommended practice to always immediately follow a call to lock with a try block, most typically in a before/after construction such as:

class X {
   private final ReentrantLock lock = new ReentrantLock();
   // ...

   public void m() {
     lock.lock();  // block until condition holds
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }
 }

From the documentation for lock() method:"If the lock is held by another thread then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired" and this is what you want to be guaranteed in your scenario.

dariosicily
  • 4,239
  • 2
  • 11
  • 17