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

java, multithreading

Solution

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.

Problem

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: - We begin waiting, and obj.wait() releases lock on obj. - Waiting thread is spuriously notified by OS - We return to checking condition (with obj lock released due to wait) - 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?

Original source