Well, I was wrong – the stating below does not apply, not in my test runs.
This mail (wot, no chickens?) from the the Java Thread mailing list is quite old, in fact it’s from 25th September 1996. Peter Welch has found out:
Enclosed is a demonstration that shows that notified threads do get
put on the back of the queue in order to regain the monitor. Before
the `wait’ method returns, the thread is made to queue up again on the
monitor (behind threads that arrived long after it first went through
that queue!). This can result in infinite overtaking and, hence,
thread starvation.
To summarize the behavior again:
Thread-1 acquires the monitor lock
Thread-1 sees the condition is not true yet -> wait()
Thread-0 acquires the monitor lock
Thread-2 contends with Thread-0 for the monitor lock
Thread-3 contends with Thread-0 for the monitor lock
Thread-4 contends with Thread-0 for the monitor lock
Thread-5 contends with Thread-0 for the monitor lock
Thread-0 turns the condition to true -> notifyAll();
Thread-0 released the monitor lock
Thread-4 acquires the monitor lock
Thread-4 enjoys his desirable state
Thread-4 releases the monitor lock
Thread-2 acquires the monitor lock
Thread-2 enjoys his desirable state
...
The thread being the first one to wait on the condition will never be the first one to regain the monitor. I knew already, that there is no fairness guarantee. What, however, is new to me, is that there is some kind of order in how the threads regain the monitor.
Why should the first thread be the one to regain the monitor lock the last? The way it’s implemented Thread-1 is never able to pass the condition and get into the desired state.
Is there some explanation for this semantic?
Important: This question is not about, whether I can rely on the mechanics I’ve discovered. I know how the waiting and signalling for Java is documented and that they clearly state, you cannot rely on this. What I am interested in, whether virtual machines implement it in this way, whether they order the threads in this certain way.
The ordering is going to be JVM specific if you are using Object’s wait/notify. The javadoc for the notify method states:
However, a
ReentrantReadWriteLockdoes support a fairness policy, and fair mode is described as: