Sleep Instead Of Wait While Locked
ID |
java.wait_instead_thread_sleep_lock |
Severity |
critical |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
concurrency, reliability |
Description
Reports a call to Thread.sleep(..) made while the enclosing code already holds a monitor: inside a synchronized block or a synchronized method.
Rationale
Thread.sleep(..) suspends the current thread without releasing any lock it holds. If that thread is inside a synchronized block or method, every other thread waiting to enter the same monitor stays blocked for the full sleep duration, even though the sleeping thread makes no progress with the lock either. This turns a short pause into a full-blown contention bottleneck, and can escalate to a deadlock-like stall under load.
Object.wait() (or java.util.concurrent.locks.Condition.await()) exists precisely for this situation: both release the monitor while the thread is parked, and a matching notify()/notifyAll() (or signal()) wakes it back up.
// Bad -- sleeps while still holding the monitor
synchronized (gate) {
while (queue.isEmpty()) {
Thread.sleep(200);
}
queue.removeFirst();
}
Remediation
Replace the polling sleep with wait() inside the same synchronized block, guarded by a while loop to handle spurious wakeups, and have the producer call notify()/notifyAll() once state changes.
// Good -- wait() releases the monitor while parked
synchronized (gate) {
while (queue.isEmpty()) {
gate.wait();
}
queue.removeFirst();
}