rewrite-static-analysis icon indicating copy to clipboard operation
rewrite-static-analysis copied to clipboard

RSPEC-2276 - "wait(...)" should be used instead of "Thread.sleep(...)" when a lock is held

Open yeikel opened this issue 1 year ago • 0 comments

If Thread.sleep(...) is called when the current thread holds a lock, it could lead to performance and scalability issues, or even worse to deadlocks because the execution of the thread holding the lock is frozen. It’s better to call wait(...) on the monitor object to temporarily release the lock and allow other threads to run.

Noncompliant Code Example



public void doSomething(){
  synchronized(monitor) {
    while(notReady()){
      Thread.sleep(200);
    }
    process();
  }
  
}

Compliant Solution



public void doSomething(){
  synchronized(monitor) {
    while(notReady()){
      monitor.wait(200);
    }
    process();
  }
  
}

https://rules.sonarsource.com/java/RSPEC-2276

yeikel avatar Feb 27 '23 23:02 yeikel