While (condition) {Object.wait ()} idiom

I know that we use this idiom to wait for a notification to handle false awakenings:

synchronized (obj) {
    while(somecond)
        obj.wait();
}

If a false awakening occurs, we will simply check the condition and return to the expectation.

But consider the situation:

  • We start to wait, and obj.wait () releases the lock on the object.
  • Waiting thread falsely notified by OS
  • We return to the verification condition (with obj blocking due to waiting)
  • obj.notify () at that moment is called correct.

Yes, the verification of conditions is very quick, and the likelihood that we can be in a verification state, and not in obj.wait(), is negligible. In this case, we may lose the call obj.notify().

Am I misunderstanding something, or can we really lose the notification using this template?

+3
source
5

obj, obj.notify(). , while , obj, while.

+8

obj.wait() , obj.notify(). obj.notify(), , . , obj.notifyAll(). , .

, obj.notify(), . , , . synchronized .

+1

Thread A , Thread B notify, Thread A notify

notify, , , Thread A - . . javadoc notify.

+1

, , , obj , obj.notify(). , , , obj.

, , obj.notify(). , obj.notify(), : , obj.notifiy() .

, , , , , , , .

+1

, , :

notify wait ing. , notify, synchronized. notify , - synchronized wait, wait - notify .

, , notify, . synchronized wait. reset , notify .

,

  • , notify invocations
  • notify

That's why I like the right processing cycle.

synchronized(obj) {
    while(somecond)
        obj.wait();
}

From the point of view of applications, there is no difference between legacy pending notifyand false awakenings generated by the JVM / OS without associated calls notify. This is why there is no attempt to prevent false awakenings of the JVM. Efforts will be wasted, as the logic will not change.

+1
source

All Articles