-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathDateFormatThreadUnsafe.qhelp
More file actions
45 lines (32 loc) · 1.5 KB
/
DateFormatThreadUnsafe.qhelp
File metadata and controls
45 lines (32 loc) · 1.5 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
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>Static fields of type <code>java.text.DateFormat</code> or its descendants
should be avoided because the class <code>DateFormat</code> is not thread-safe.
</p>
</overview>
<recommendation>
<p>Use instance fields instead and synchronize access where necessary.</p>
</recommendation>
<example>
<p>In the following example, <code>DateFormattingThread</code> declares a static field <code>dateF</code>
of type <code>DateFormat</code>. When instances of <code>DateFormattingThread</code> are created
and run by <code>DateFormatThreadUnsafe</code>, erroneous results are output because <code>dateF</code>
is shared by all instances of <code>DateFormattingThread</code>.</p>
<sample src="DateFormatThreadUnsafe.java" />
<p>In the following modification of the above example, <code>DateFormattingThread</code> declares an
<i>instance</i> field <code>dateF</code> of type <code>DateFormat</code>. When instances of
<code>DateFormattingThread</code> are created and run by <code>DateFormatThreadUnsafeFix</code>,
correct results are output because there is a separate instance of <code>dateF</code> for each
instance of <code>DateFormattingThread</code>.</p>
<sample src="DateFormatThreadUnsafeGood.java" />
</example>
<references>
<li>
Java API Specification:
<a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DateFormat.html#synchronization">java.text.DateFormat synchronization</a>.
</li>
</references>
</qhelp>