Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wait() , notify() - which thread first unlock?

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() ?

like image 580
vico Avatar asked Dec 11 '22 14:12

vico


2 Answers

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.

like image 196
Jon Skeet Avatar answered Dec 13 '22 04:12

Jon Skeet


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.

like image 35
kgeorgiy Avatar answered Dec 13 '22 03:12

kgeorgiy