-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathNotifyWithoutSynch.qhelp
More file actions
54 lines (41 loc) · 1.8 KB
/
NotifyWithoutSynch.qhelp
File metadata and controls
54 lines (41 loc) · 1.8 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
48
49
50
51
52
53
54
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>The methods <code>notify</code>, <code>notifyAll</code>, and <code>wait</code>
should only be called by a thread that is the owner of the object's monitor
(intrinsic lock). In other words, the methods should only be called from within
a synchronized statement or method. Otherwise the method call will throw
<code>IllegalMonitorStateException</code>.
</p>
</overview>
<recommendation>
<p>Ensure that calls to <code>notify</code>, <code>notifyAll</code>,
or <code>wait</code> are called from within a synchronized statement or method.
</p>
</recommendation>
<example>
<p>In the following example, the methods <code>produce</code> and <code>consume</code> use
<code>wait</code> and <code>notifyAll</code> to communicate. However, the <code>consume</code>
method is not synchronized, so the calls to <code>wait</code> and <code>notifyAll</code> will
always throw an exception.</p>
<sample src="NotifyWithoutSynch.java" />
<p>To fix this example, add the <code>synchronized</code> keyword to the
declaration of the <code>consume</code> method.</p>
</example>
<references>
<li>
J. Bloch.
<em>Effective Java (second edition)</em>, p. 276.
Addison-Wesley, 2008.
</li>
<li>
Java API Specification:
<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#notify()">Object.notify()</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/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#wait(long)">Object.wait(long)</a>.
</li>
</references>
</qhelp>