Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which thread does notify wake up? [duplicate]

Imagine I have 3 threads with a wait condition, and a 4th thread with a notify condition.

Now, all 3 wait threads run and enter a waiting state. Once this is done, the 4th thread runs and calls notify once.

How will the notify determine which thread to wake up? Is it the thread that called wait first thread, the thread that called wait last, or is it based on some other condition?

Assume that wait and notify uses same lock.

like image 885
Jithin KS Avatar asked Jul 26 '17 08:07

Jithin KS


People also ask

How JVM determines which thread should wake up on notify ()?

See documentation for notify() method. Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.

What are wait () notify () notifyAll ()?

The notify() method wakes up a single thread that is waiting on that object's monitor. The notifyAll() method wakes up all threads that are waiting on that object's monitor. A thread waits on an object's monitor by calling one of the wait() method.

What is notify method in thread?

The thread class notify() method is used to wake up a single thread. If multiple threads are waiting for notification, and we use the notify() method, only one thread will receive the notification, and the others will have to wait for more. This method does not return any value.

Which method wakes up when only one thread waiting on the object and that thread start execution?

notify method wakes up only one thread waiting on the object and that thread starts execution. So if there are multiple threads waiting for an object, this method will wake up only one of them. The choice of the thread to wake depends on the OS implementation of thread management.


1 Answers

To my knowledge, there is no special bookkeeping - meaning that the selection is made "randomly".

So says the javadoc:

If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.

Thus it would be theoretically possible that a JVM implementation decides to enact a specific order; but as shown - by default you can't expect any order. So you shouldn't write code that relies on such an specific order either.

like image 170
GhostCat Avatar answered Sep 18 '22 12:09

GhostCat