notify() implementation in Oracle's jvm

382 views Asked by At

I am under the impression that most people use only the jvm implementation given by the Oracle (originally from Sun microsystems). Correct me if I am wrong.

When I went through the API for notify(), it says :

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.

I would like to know in what order the waiting threads will be invoked when notify() is called in the Oracle's jvm.

You might wonder why I am not considering to use notifyAll() and just stop worrying. But why should I invoke all the waiting threads unnecessarily when I can do with invoking just one thread with notify()? Even if I use notifyAll(), I have no control which of the waiting threads will get the monitor.

Oracle should have documented how it is implemented in its own implementation right in the api link given above.

3

There are 3 answers

0
TwoThe On

The order of execution with Threads is undefined.

If you write any code based on the assumption that you can predict the order of execution, it will run on a single machine at best. So how Oracle actually implemented it is - except for a research case - irrelevant, as it probably is implemented differently on the next machine and even on the next version of the Oracle JVM.

If you need a more fine-grain control, then you need to adjust your architecture and use the classes from the concurrent package in a proper way. Synchronized/wait/notify is just a very basic "brute-force" implementation of thread-synchronization with many pit-falls and restrictions.

0
Evgeniy Dorofeev On

You can rely only on what API says and API does not guarantee any specific order. If you need threads to wake up in a certain order use ReentrantLock in fair mode then this lock's Condition.signal() will wake the thread waiting for this Condition longest.

0
Mikhail On

You can use ReentrantLock(boolean fair) with fairness flag in constructor. Conditions created from a such lock are also fair:

Creates an instance of ReentrantLock with the given fairness policy.

and

The ordering of lock reacquisition for threads returning from waiting methods is the same as for threads initially acquiring the lock, which is in the default case not specified, but for fair locks favors those threads that have been waiting the longest.