Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I know, that we use this idiom for waiting for notification to handle spurious wakeups:

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

If a spurious wake up arises, we'll just check the state and return back to waiting.

But, consider the situation:

  1. We begin waiting, and obj.wait() releases lock on obj.
  2. Waiting thread is spuriously notified by OS
  3. We return to checking condition (with obj lock released due to wait)
  4. obj.notify() is called right in that moment.

Yes, condition checking is extremely fast and chances, that we can be in condition checking and not in obj.wait(), are negligibly small. In that case we can loose obj.notify() call.

Am I misunderstanding something, or we really can loose notification using this pattern?

like image 495
Oroboros102 Avatar asked Jun 17 '26 14:06

Oroboros102


2 Answers

Another thread needs the lock on obj to be able to call obj.notify(). And it can't have it if your thread is in the while loop not waiting, since your thread also needs the lock on obj to be in the while loop.

like image 158
JB Nizet Avatar answered Jun 19 '26 04:06

JB Nizet


The call to obj.wait() will not return until an obj.notify() has been called. However, you might fail to respond to an obj.notify() if another thread is also waiting and the system decides to notify that thread instead. If you want to avoid that, you can use obj.notifyAll(). If only one thread is waiting, you cannot lose the notification with this pattern.

Note that the other thread cannot call obj.notify() unless it holds the lock. If this thread is busy checking the condition, then it has the lock and the other thread cannot issue a notification. The synchronized block is essential to the operation.

like image 32
Ted Hopp Avatar answered Jun 19 '26 04:06

Ted Hopp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!