synchronized, monitors, wait and notify question 28 of 180 mid
Why must wait() be called inside a loop?
- Because
wait()can throw at random - Correct: Because of spurious wakeups, and because another thread may consume the condition between the notify and the waiter reacquiring the lock
- Because
notify()only wakes one thread - Only if you use
notifyAll()
Two independent reasons, and the second is the important one. The JLS permits spurious wakeups, so a
wait() may return with nothing having happened. Worse, a woken waiter must reacquire the monitor
before returning, and in that window a third thread can take the item that was just made available.
The condition that was true at notify() time is false again by the time you resume.
synchronized (lock) {
while (queue.isEmpty()) { // while, never if
lock.wait();
}
return queue.remove();
}
Rewriting that while as an if produces a bug that survives every test and fails under load. This
is the guarded suspension pattern, and Condition.await() has exactly the same rule.
Quiz yourself on synchronized, monitors, wait and notify Suggest a correction