wait()/notify()/notifyAll() Outside Synchronized Context

ID

java.wait_notify_outside_synchronized

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:362, concurrency, reliability

Description

Reports calls to Object.wait(), Object.notify(), and Object.notifyAll() that are not enclosed in a synchronized block or synchronized method.

Rationale

The Java Language Specification requires that a thread must own the object’s monitor before calling wait(), notify(), or notifyAll() on it. Calling these methods outside a synchronized context throws IllegalMonitorStateException at runtime. This is a latent concurrency bug that may not surface until the code runs under contention.

// Bad -- will throw IllegalMonitorStateException
public void awaitReady(Object monitor) throws InterruptedException {
    monitor.wait();
}

Remediation

Wrap the call in a synchronized block that locks the same object, or declare the enclosing method as synchronized.

// Good -- monitor is held
public void awaitReady(Object monitor) throws InterruptedException {
    synchronized (monitor) {
        while (!ready) {
            monitor.wait();
        }
    }
}