-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathSleepWithLock.qhelp
More file actions
47 lines (35 loc) · 1.98 KB
/
SleepWithLock.qhelp
File metadata and controls
47 lines (35 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>Calling <code>Thread.sleep</code> with a lock held may lead to very poor performance
or even deadlock. This is because <code>Thread.sleep</code> does not cause a thread to release its locks.</p>
</overview>
<recommendation>
<p>
<code>Thread.sleep</code> should be called only outside of a <code>synchronized</code> block.
However, a better way for threads to yield execution time to other threads may be to use either of
the following solutions:</p>
<ul>
<li>The <code>java.util.concurrent</code> library</li>
<li>The <code>wait</code> and <code>notifyAll</code> methods</li>
</ul>
</recommendation>
<example>
<p>In the following example of the problem, two threads, <code>StorageThread</code> and <code>OtherThread</code>,
are started. Both threads output a message to show that they have started but then
<code>StorageThread</code> locks <code>counter</code> and goes to sleep. The lock prevents
<code>OtherThread</code> from locking <code>counter</code>, so it has to wait until
<code>StorageThread</code> has woken up and unlocked <code>counter</code> before it can continue.</p>
<sample src="SleepWithLock.java" />
<p>To avoid this problem, <code>StorageThread</code> should call <code>Thread.sleep</code> outside
the <code>synchronized</code> block instead, so that <code>counter</code> is unlocked.</p>
</example>
<references>
<li>Java API Specification: <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#sleep(long)">Thread.sleep()</a>,
<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#wait()">Object.wait()</a>,
<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#notifyAll()">Object.notifyAll()</a>,
<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/package-summary.html">java.util.concurrent</a>.</li>
</references>
</qhelp>