Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object vs Condition, wait() vs await()

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?

edit: the solution: enter image description here

How would I implement this with the Condition?

like image 923
Cherry Avatar asked Aug 31 '25 04:08

Cherry


1 Answers

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();
}
like image 109
xingbin Avatar answered Sep 03 '25 18:09

xingbin