This question is inspired by this other question.
If multiple threads are waiting on a synchronized
block, and the lock becomes available, who goes first? Is it by thread priority (and then first-come-first-served)?
And do the same rules apply for notify
(with multiple wait
ing threads)?
The wait function doesn't release "all locks", but it does release the lock associated with the object on which wait is invoked.
As Michael Borgwardt points out, wait/notify is all about communication between threads, so you'll always end up with a race condition similar to the one described above. This is why the "only wait inside synchronized" rule is enforced.
Calling notify() or notifyAll() methods issues a notification to a single or multiple threads that a condition has changed and once the notification thread leaves the synchronized block, all the threads which are waiting for fight for object lock on which they are waiting and lucky thread returns from wait() method ...
Explanation: Option A is correct because the notifyAll() method (along with wait() and notify()) must always be called from within a synchronized context. Option B is incorrect because to call wait(), the thread must own the lock on the object that wait() is being invoked on, not the other way around.
According to this guy: http://tutorials.jenkov.com/java-concurrency/starvation-and-fairness.html
Java issues no guarantees about the sequence. So I guess it is not based on thread priority
I'll try to look further for an explanation on how Java actually decides who goes first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With