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
?
When a thread calls wait() , it's temporarily releasing the monitor (lock) of the object until it receives a notification from another thread. This way, a thread can willingly give control (that it has, in the first place) of the object's monitor to another thread.
Monitors. Monitor is a synchronization construct that allows threads to have both mutual exclusion (using locks) and cooperation i.e. the ability to make threads wait for certain condition to be true (using wait-set).
In java, synchronized methods and blocks allow only one thread to acquire the lock on a resource at a time. So, when wait() method is called by a thread, then it gives up the lock on that resource and goes to sleep until some other thread enters the same monitor and invokes the notify() or notifyAll() method.
Java's implementation of a monitor mechanism relies on two concepts – the entry set and the wait set. In literature, authors use a building and exclusive room analogy to represent the monitor mechanism. In this analogy, only one person can be present in an exclusive room at a time.
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:
Let thread t be the thread executing the wait method on object m, and let n be the number of lock actions by t on m that have not been matched by unlock actions. One of the following actions occurs.
- [...]
Otherwise, the following sequence occurs:
- Thread t is added to the wait set of object m, and performs n unlock actions on m.
- [...]
From the Java API documentation of the Object class:
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
So, calling b.wait()
releases the lock on b
only.
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