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();
}
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.
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.
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 .
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With