Blue Diamond
Blue Diamond

Reputation: 3069

Notification in Java thread synchronization

When there are multiple threads in waiting state; and if I call notify() rather than calling notifyAll() Which one is going to be notified among several threads in waiting state?

Upvotes: 1

Views: 96

Answers (3)

m0skit0
m0skit0

Reputation: 25874

That's undefined behavior. Anyone could be picked up. From the JavaDoc:

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.

And yes, this can lead to thread starvation.

Upvotes: 3

Gray
Gray

Reputation: 116938

When there are multiple threads in waiting state; and if I call notify() rather than calling notifyAll() Which one is going to be notified among several threads in waiting state?

Although as has been mentioned, the particular behavior is not defined by the Java spec, I suspect that JDC implementations will take the thread at the front of the WAIT queue for the particular monitor. However this should not be relied on.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 692271

The javadoc says:

The choice is arbitrary and occurs at the discretion of the implementation.

Upvotes: 1

Related Questions