4

Trying to understand wait() and notify(). I know when thread A went to wait() it will be waked up by notify() from other thread.

But what will happens if threads A,B,C went to wait() in represented order? Who will be waked up by notify()? According to my experiments A thread will be waked up at first. I'm right?

Does it means that system knows in which order threads went to wait() ?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
vico
  • 17,051
  • 45
  • 159
  • 315
  • There is no such guarantee, see also http://stackoverflow.com/questions/30471285/what-is-the-difference-between-wait-notify-and-wait-interrupt and http://stackoverflow.com/questions/37026/java-notify-vs-notifyall-all-over-again – Mark Rotteveel Nov 05 '16 at 10:14

5 Answers5

8

From the documentation for notify(), emphasis mine:

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. A thread waits on an object's monitor by calling one of the wait methods.

Some other APIs, such as Semaphore, have a concept of "fairness", where you can ensure that threads do proceed in the order in which they blocked.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Section 17.2.2 Notification of Java Language Specification:

There is no guarantee about which thread in the wait set is selected.

So, observed behavior is not guaranteed and should not be relied upon.

kgeorgiy
  • 1,477
  • 7
  • 9
2

No, the VM does not know in which order the threads were put in Waiting state.

When you call notify(), one of them will be back to Alive/Runnable state and there is no way to know which one the VM will choose.

Sometimes they can run in the order they were put in Waiting state, but the specification does not guarantee that. So in a different VMs you can have a completely different results or even in the same VM, if you run the code multiple times.

1

No, there is no guarantee about the order. The javadoc of the notify method is pretty clear on this:

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. A thread waits on an object's monitor by calling one of the wait methods.

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
1

There's no such an order. Either thread has an equal opportunity to get into runnable state. Actually JVM/OS can see them only as a set of waiting threads, they don't know any order.

In terms of your experiment, to get into a fair conclusion, actually you have to perform it for a huge number of times.

In threads, you can expect an order (FIFO), only if you are using something like a strong Semaphore. Then these threads are put into a waiting queue and fist comer would be first served.

Supun Wijerathne
  • 11,964
  • 10
  • 61
  • 87