Condition.await() Must Be Called Inside a While Loop

ID

java.condition_await_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 Condition.await() that are not enclosed in a while loop.

Rationale

The Condition.await() method can return spuriously — that is, without the condition actually being satisfied. The Java specification explicitly warns about this and recommends always calling await() inside a loop that rechecks the 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
if (flag) {
    condition.await();
}

Remediation

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

// Good -- condition is rechecked after wakeup
while (flag) {
    condition.await();
}