Java Concurrency Interview

synchronized, monitors, wait and notify question 28 of 180 mid

Why must wait() be called inside a loop?

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.

wait-notify guarded-suspension

Quiz yourself on synchronized, monitors, wait and notify Suggest a correction