Object.wait() Must Be Called Inside a While Loop

ID

java.wait_must_be_in_while

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:367, concurrency, reliability

Description

Reports calls to Object.wait() that are not enclosed in a while loop.

Rationale

The Object.wait() method can return spuriously — that is, without notify() or notifyAll() being called. The Java specification explicitly warns about this and recommends always calling wait() inside a loop that rechecks the guarding condition. Using if instead of while means a spurious wakeup will cause the thread to proceed with stale or invalid state.

// Bad -- spurious wakeup skips the condition check
synchronized (monitor) {
    if (!ready) {
        monitor.wait();
    }
}

Remediation

Always wrap the wait() call in a while loop:

// Good -- condition is rechecked after wakeup
synchronized (monitor) {
    while (!ready) {
        monitor.wait();
    }
}