Reputation: 81
In the solution to an programming exercise concerning locks, I've noticed they were using an Object to syncronize on, so something like:
Lock lock = new ReentrantLock();
Object obj = new Object();
and in a method:
synchronized(obj){
obj.wait();}
my question is, could I have used a Condition instead, let's say:
Condition cond = lock.newCondition();
and then use, in the method,
cond.await()
instead, without putting it in a synhronized block?
How would I implement this with the Condition?
Upvotes: 4
Views: 4926
Reputation: 28289
Yes. But you have to aquire the lock first. See the doc of Condition.await():
The current thread is assumed to hold the lock associated with this Condition when this method is called. It is up to the implementation to determine if this is the case and if not, how to respond. Typically, an exception will be thrown (such as IllegalMonitorStateException) and the implementation must document that fact.
synchronized (obj) {
while (<condition does not hold>)
obj.wait();
... // Perform action appropriate to condition
}
is similar with
ReentrantLock lock = new ReentrantLock();
Condition cond = lock.newCondition();
lock.lock();
try {
while (<condition does not hold>)
cond.await();
}
} finally {
lock.unlock();
}
Upvotes: 4