== 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

[source,java,diff-id=1,diff-type=noncompliant]
----
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

[source,java,diff-id=1,diff-type=compliant]
----
public void doSomething(){
  synchronized(monitor) {
    while(notReady()){
      monitor.wait(200); // Compliant, the current monitor is released.
    }
    process();
  }
  ...
}
----


== Resources

* https://wiki.sei.cmu.edu/confluence/x/YTdGBQ[CERT, LCK09-J.] - Do not perform operations that can block while holding a lock


ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Replace the call to "Thread.sleep(...)" with a call to "wait(...)".


'''
== Comments And Links
(visible only on this page)

=== on 15 Feb 2016, 17:17:18 Ann Campbell wrote:
This RSpec exlicitly _not_ expanded to cover full scope of CERT, LCK09-J. because the other operations _can_ lead to problems (but may not), whereas for `sleep` there is a problem sure.

endif::env-github,rspecator-view[]
