Thread.sleep() In Loop (Busy-Wait)
ID |
java.sleep_in_loop_busy_wait |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
concurrency, efficiency |
Description
Reports calls to Thread.sleep() inside loop bodies (for, while, do-while, enhanced-for). This is a busy-wait anti-pattern that wastes CPU time and is fragile.
Rationale
Polling with Thread.sleep() in a loop is a common but inefficient pattern. The thread holds resources while sleeping, the polling interval is either too short (CPU waste) or too long (latency). Proper concurrency primitives signal exactly when work is available.
// Bad - busy-wait polling
while (!ready) {
Thread.sleep(100);
}
Remediation
Use condition variables, CountDownLatch, CompletableFuture, or a ScheduledExecutorService.
// Good - wait on a condition
synchronized (lock) {
while (!ready) {
lock.wait();
}
}