Before a thread can wait
on an object, it has to acquire a monitor on that object. The monitor is then released, and the thread attempts to re-acquired it once it awakes.
But what happens to other monitors the thread holds when it calls wait
?
Consider this example:
Object a = // ... Object b = // ... synchronized(a) { synchronized(b) { b.wait(); // continue } }
When the thread calls b.wait()
, will it release the locks on both a
and b
, or only b
?
Only
b
.The authoritarian source for these type of questions is the Java Language Specification. The relevant section in this case is 17.8 Wait Sets and Notification:
From the Java API documentation of the Object class:
So, calling
b.wait()
releases the lock onb
only.AFAIK only b. It's a classic source of deadlocks.