Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition - should unlock before await?

Could you tell me if I should release lock before await on condition?

try {
    lock.lock();
    while (isNotEmpty()) {
        condition.await();
    }
} finally {
    lock.unlock();
}

Or

try {
    lock.lock();
    while (isNotEmpty()) {
        lock.unlock();
        condition.await();
    }
} finally {
    lock.unlock();
}
like image 957
Heniek Avatar asked Jul 03 '12 10:07

Heniek


People also ask

Does condition await release lock?

The key property that waiting for a condition provides is that it atomically releases the associated lock and suspends the current thread, just like Object.

Why must a thread be holding a lock to wait on a condition variable?

The lock is used to enforce mutual exclusion. The condition variables are used as wait queues so that other threads can sleep while the lock is held. Thus condition variables make it so that if a thread can safely go to sleep and be guaranteed that when they wake up they will have control of the lock again.

What is explicit lock in java?

Another way to ensure exclusive access to a section of code is to use an explicit lock. An explicit lock is more flexible than using the synchronized keyword because the lock can span a few statements in a method, or multiple methods in addition to the scopes (block and method) supported by synchronized .

Why are locks helpful when using threads in Java?

The idea behind read-write locks is that it's usually safe to read mutable variables concurrently as long as nobody is writing to this variable. So the read-lock can be held simultaneously by multiple threads as long as no threads hold the write-lock.


2 Answers

No, you do not need to explicitly release the lock before calling await, await will release it automatically. From javadoc:

The lock associated with this Condition is atomically released and the current thread becomes disabled for thread scheduling purposes[...]

And:

The current thread is assumed to hold the lock associated with this Condition when this method is called.

like image 158
Tudor Avatar answered Oct 03 '22 04:10

Tudor


You can only await() on a Condition when you have lock()ed the associated Lock

Why don't you have a condition for isEmpty to make your conditions clearer.

See the example in the Javadoc. http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html

e.g.

 lock.lock();
 try {
   while (count > 0)
     isEmpty.await();
   // do something when empty.
 } finally {
   lock.unlock();
 }
like image 26
Peter Lawrey Avatar answered Oct 03 '22 03:10

Peter Lawrey