Thilo
Thilo

Reputation: 262514

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

Upvotes: 15

Views: 10716

Answers (4)

andersoj
andersoj

Reputation: 22884

Someone else mentioned the availability of fair locks. If you really care who goes first, then you may have a real-time problem. In that case, you can make use of RTSJ, wherein the ordering and other semantics of lock acquisition is specified. The specifics are available in the RTSJ Spec under Synchronization. Quoting from the rationale section:

Java's rules for synchronized code provide a means for mutual exclusion but do not prevent unbounded priority inversions and thus are insufficient for real-time applications. This specification strengthens the semantics for synchronized code by mandating priority inversion control, in particular by furnishing classes for priority inheritance and priority ceiling emulation. Priority inheritance is more widely implemented in real-time operating systems and thus is required and is the initial default mechanism in this specification.

Upvotes: 6

punkers
punkers

Reputation: 107

It depends on thread priority and thread scheduling algorithm and also the lock on the synchronized block is not "fair". This means that if there are 2 waiting threads with the same priority and the first thread waited more than the second thread that doesn't necessarily mean that the first thread will be executed first.

Upvotes: 0

Mikkel Gadegaard
Mikkel Gadegaard

Reputation: 386

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.

Upvotes: 9

Jigar Joshi
Jigar Joshi

Reputation: 240900

for your second Question

one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.

From http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#notify()

Upvotes: 1

Related Questions