GBa
GBa

Reputation: 18447

When is monitor released in java

If I have the code:

ReentrantLock lock = new ReentrantLock();
Condition waiting = lock.newCondition();

Thread 1:

    value = default;
    lock.lock();
    try {
        waiting.await(new Long(timeout).longValue(), TimeUnit.SECONDS);
    } catch (InterruptedException e) {

        } finally {
            lock.unlock();
        }

Thread 2:

  lock.lock();
  //set value
  waiting.signalAll();
  lock.unlock();    

Am I correct in that the monitor on the lock is released when await is called, allowing the event driven thread 2 to run if needed? If thread 2 happens to run, when will thread 1 be able to resume, upon signalAll(), or lock.unlock()? If thread 2 is signaling a wakeup, but still has a lock, how does that work??

Upvotes: 2

Views: 294

Answers (1)

John Vint
John Vint

Reputation: 40256

The lock is in fact released when invoking await. When signalAll is called, no waiting threads will awake until the signalling thread unlocks

However, it is important to differentiate Java object monitors with Java Locks. They are separate constructs, in fact the ReentrantLock/Condition itself can be a monitor in a different context then what you are working with (for example if instead of await you called wait you would get the obvious IllegalMonitorStateException).

Upvotes: 3

Related Questions