Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does notify/notifyall release the lock being held

I am confused a bit about wait and notify/notifyAll.

I know there is a lock for every java object. I know wait will release the lock for other thread. How about notify/notifyall? Does notify/notifyAll release the lock it is holding for other thread?

like image 913
icn Avatar asked May 14 '11 01:05

icn


People also ask

What is the difference between notify () and notifyAll ()?

In case of multiThreading notify() method sends the notification to only one thread among the multiple waiting threads which are waiting for lock. While notifyAll() methods in the same context sends the notification to all waiting threads instead of single one thread.

Which method releases the lock immediately?

The tryLock() method It returns the lock immediately with the Boolean value true when the lock is available. It returns the Boolean value false when the lock is not available.

Does wait () Release lock from synchronized block?

The wait function doesn't release "all locks", but it does release the lock associated with the object on which wait is invoked.

What does notify all do?

notifyAll() wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods. The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object.


1 Answers

No -- notify/notifyAll don't release locks like wait does. The awakened thread can't run until the code which called notify releases its lock.

This is what the Javadoc says:

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.

like image 182
Daniel Lubarov Avatar answered Sep 23 '22 19:09

Daniel Lubarov