Jithin KS Jithin KS - 2 years ago 107
Java Question

Which thread does notify wake up?

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download