Why is this an issue?
In a multithreaded environment, a thread may need to wait for a particular condition to become true. One way of pausing execution in Java is
Thread.sleep(…)
.
If a thread that holds a lock calls Thread.sleep(…)
, no other thread can acquire said lock. This can lead to performance and
scalability issues, in the worst case leading to deadlocks.
How to fix it
Call wait(…)
on the monitor object instead of using Thread.sleep(…)
. While wait(…)
is executed, the lock
is temporarily released and hence other threads can run in the meantime.
Code examples
Noncompliant code example
public void doSomething(){
synchronized(monitor) {
while(notReady()){
Thread.sleep(200); // Noncompliant, any other thread synchronizing on monitor is blocked from running while the first thread sleeps.
}
process();
}
...
}
Compliant solution
public void doSomething(){
synchronized(monitor) {
while(notReady()){
monitor.wait(200); // Compliant, the current monitor is released.
}
process();
}
...
}
Resources
- CERT, LCK09-J. - Do not perform operations that can block while holding a lock