Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: waiting on synchronized block, who goes first?

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 waiting threads)?

like image 685
Thilo Avatar asked Oct 15 '10 07:10

Thilo


People also ask

Does wait () Release lock from synchronized block?

The wait function doesn't release "all locks", but it does release the lock associated with the object on which wait is invoked.

Why must wait () always be in synchronized block?

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.

Why wait notify called from synchronized?

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 ...

Is it necessary to call wait and notify from synchronized 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.


1 Answers

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.

like image 97
Mikkel Gadegaard Avatar answered Oct 13 '22 17:10

Mikkel Gadegaard