Which thread notifies of awakening?

Imagine that I have 3 threads with a wait condition and a 4th thread with a notification condition.

Now all three waiting threads are started and enter the standby state. Once this is done, the 4th thread is executed and calls are notified once.

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

Suppose wait and notify use the same lock.

+5
source share
2 answers

As far as I know, special bookkeeping does not exist - this means that the choice is made "randomly."

So says javadoc :

If any threads are waiting on this object, one of them is selected for awakening. The choice is arbitrary and is at the discretion of the implementation.

Thus, it is theoretically possible that the JVM implementation decides to accept a specific order; but, as shown, by default you cannot expect any order. Thus, you should not write code that also relies on such a specific order.

+7
source

See the documentation for the notify () method.

Wakes up one thread waiting for this object monitor. If any threads are waiting on this object, one of them is selected wakes up. The choice is arbitrary and is at the discretion of the implementation .

0
source

Source: https://habr.com/ru/post/1270211/


All Articles