Which thread does notify wake up? [duplicate]
Asked Answered
S

2

7

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.

Sole answered 26/7, 2017 at 8:43 Comment(1)
A random one, at least as far as you're concerned. From there javadocs: "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."Homey
D
9

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.

Dayfly answered 26/7, 2017 at 8:50 Comment(0)
C
1

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.

Cystic answered 26/7, 2017 at 8:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.