Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

notify() implementation in Oracle's jvm

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.

like image 521
Arul Jose Avatar asked Jan 23 '26 11:01

Arul Jose


2 Answers

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.

like image 166
TwoThe Avatar answered Jan 25 '26 00:01

TwoThe


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.

like image 44
Evgeniy Dorofeev Avatar answered Jan 25 '26 01:01

Evgeniy Dorofeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!