Repository navigation
Expand file tree
/
Copy pathmultithreading.xml
More file actions
618 lines (565 loc) · 23.2 KB
/
Copy pathmultithreading.xml
File metadata and controls
618 lines (565 loc) · 23.2 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="Multithreading"
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
<description>
Rules that flag issues when dealing with multiple threads of execution.
</description>
<rule name="AvoidSynchronizedAtMethodLevel"
language="java"
since="3.0"
message="Use block level locking rather than method level synchronization"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_multithreading.html#avoidsynchronizedatmethodlevel">
<description>
Method-level synchronization will pin virtual threads and can cause performance problems. Additionally, it can cause
problems when new code is added to the method. Block-level ReentrantLock helps to ensure that only the code that
needs mutual exclusion will be locked.
See also {% rule AvoidSynchronizedStatement %}.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>//MethodDeclaration[pmd-java:modifiers() = "synchronized"]</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo {
// Try to avoid this:
synchronized void foo() {
// code, that doesn't need synchronization
// ...
// code, that requires synchronization
if (!sharedData.has("bar")) {
sharedData.add("bar");
}
// more code, that doesn't need synchronization
// ...
}
// Prefer this:
Lock instanceLock = new ReentrantLock();
void bar() {
// code, that doesn't need synchronization
// ...
instanceLock.lock();
try {
// code, that requires synchronization
if (!sharedData.has("bar")) {
sharedData.add("bar");
}
} finally {
instanceLock.unlock();
}
// more code, that doesn't need synchronization
// ...
}
// Or prefer this with tryLock:
Lock instanceLock = new ReentrantLock();
void bar() {
// code, that doesn't need synchronization
// ...
if (instanceLock.tryLock(10, TimeUnit.SECONDS)) {
try {
// code, that requires synchronization
if (!sharedData.has("bar")) {
sharedData.add("bar");
}
} finally {
instanceLock.unlock();
}
} else {
// unable to acquire the lock
}
// more code, that doesn't need synchronization
// ...
}
]]>
</example>
<example><![CDATA[
// Try to avoid this for static methods:
static synchronized void fooStatic() {
}
// Prefer this:
private static Lock CLASS_LOCK = new ReentrantLock();
static void barStatic() {
// code, that doesn't need synchronization
// ...
CLASS_LOCK.lock();
try {
// code, that requires synchronization
} finally {
CLASS_LOCK.unlock();
}
// more code, that doesn't need synchronization
// ...
}
}
]]>
</example>
</rule>
<rule name="AvoidSynchronizedStatement"
language="java"
since="7.5.0"
message="Use ReentrantLock rather than synchronization"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_multithreading.html#avoidsynchronizedstatement">
<description>
Reports any synchronization statements.
Virtual threads (introduced by Java 21 via [JEP 444](https://openjdk.org/jeps/444)) are pinned to their
carrier thread when executing code protected by `synchronized` (either synchronized blocks or synchronized
methods). When the virtual threads are blocked by I/O and need to wait, the carrier thread stays unavailable
for other virtual threads. If this happens with all carrier threads, no new virtual threads can be
executed and this can cause performance problems.
With Java 24 ([JEP 491](https://openjdk.org/jeps/491)) virtual threads can release their carrier thread,
when they are blocked by I/O inside a synchronized block. The situation, that all carrier threads are
exhausted, should be much less likely.
Note: Thread pinning still occurs, if the virtual thread is calling native methods inside a synchronized
block.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>//SynchronizedStatement</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo {
// Try to avoid this:
void foo() {
// code that doesn't need mutual exclusion
synchronized(this) {
// code that requires mutual exclusion
}
// more code that doesn't need mutual exclusion
}
// Prefer this:
Lock instanceLock = new ReentrantLock();
void foo() {
// code that doesn't need mutual exclusion
instanceLock.lock();
try {
// code that requires mutual exclusion
} finally {
instanceLock.unlock();
}
// more code that doesn't need mutual exclusion
}
// Or prefer this with tryLock:
Lock instanceLock = new ReentrantLock();
void foo() {
// code that doesn't need mutual exclusion
if (instanceLock.tryLock(10, TimeUnit.SECONDS)) {
try {
// code that requires mutual exclusion
} finally {
instanceLock.unlock();
}
} else {
// unable to acquire the lock
}
// more code that doesn't need mutual exclusion
}
}
]]>
</example>
</rule>
<rule name="AvoidThreadGroup"
language="java"
since="3.6"
message="Avoid using java.lang.ThreadGroup; it is not thread safe"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_multithreading.html#avoidthreadgroup">
<description>
Avoid using java.lang.ThreadGroup; although it is intended to be used in a threaded environment
it contains methods that are not thread-safe.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ConstructorCall/ClassType[pmd-java:typeIs('java.lang.ThreadGroup')]
| //MethodCall[@MethodName = 'getThreadGroup']
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Bar {
void buz() {
ThreadGroup tg = new ThreadGroup("My threadgroup");
tg = new ThreadGroup(tg, "my thread group");
tg = Thread.currentThread().getThreadGroup();
tg = System.getSecurityManager().getThreadGroup();
}
}
]]>
</example>
</rule>
<rule name="AvoidUsingVolatile"
language="java"
since="4.1"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
message="Use of modifier volatile is not recommended."
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_multithreading.html#avoidusingvolatile">
<description>
The `volatile` modifier is an extremely low-level concurrency tool (like `notify` and `wait`).
It makes sure that all threads see a consistent value for a field, and it establishes a happens-before
relationship: everything the writing thread did before the volatile write becomes visible to any thread
that afterwards reads the field.
What `volatile` does **not** do:
* It doesn't make updates atomic. Read and write remain separate operations, so `counter++` is a read,
an increment and a write - two threads can interleave and lose an update. The same applies to every
check-then-act idiom.
* On a reference or array field, it only covers the reference itself. Writes to the referenced object's
fields, or to the array's elements, are not covered.
Using `volatile` correctly requires more knowledge of the Java Memory Model than most Java developers have.
Therefore, most Java developers shouldn't use it. Instead, use the higher-level classes from `java.util.concurrent`,
especially the Atomic wrapper classes:
* instead of a volatile `boolean`, `int`, `long` or reference: `AtomicBoolean`, `AtomicInteger`, `AtomicLong`,
`AtomicReference`
* instead of a volatile array: `AtomicIntegerArray`, `AtomicLongArray`, `AtomicReferenceArray`
* for counters under contention: `LongAdder`, `DoubleAdder`
* for a value that never changes after construction: `final`
* for shared collections: the concurrent collections, e.g. `ConcurrentHashMap`
A related trap concerns 64-bit fields: a write to a non-volatile `long` or `double` field is not required to be
atomic (JLS §17.7). The JVM may split it into two separate 32-bit writes, so another thread can read a value
assembled from two different writes - a value nobody ever wrote. Declaring the field `volatile` does fix this
specific problem, but it still leaves `++` and `+=` non-atomic. `AtomicLong` fixes both and is the better default.
(There is no `AtomicDouble` in the JDK; use `DoubleAdder` or an `AtomicReference<Double>`.)
Note that this rule allows no exceptions. This is intentional. Valid uses exist but are rare (e.g. {% rule DoubleCheckedLocking %}). If yours is one
of them, suppress the violation explicitly with `// NOPMD` or `@SuppressWarnings("PMD.AvoidUsingVolatile")`
and a comment explaining why.
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>//FieldDeclaration[pmd-java:modifiers() = "volatile"]</value>
</property>
</properties>
<example>
<![CDATA[
public class Data {
private volatile String var1; // not suggested
private AtomicReference<String> var2; // preferred
}
]]>
</example>
</rule>
<rule name="DoNotUseThreads"
language="java"
since="4.1"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
message="To be compliant to J2EE, a webapp should not use any thread."
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_multithreading.html#donotusethreads">
<description>
The J2EE specification explicitly forbids the use of threads. Threads are resources, that should be managed and monitored by the J2EE server.
If the application creates threads on its own or uses own custom thread pools, then these threads are not managed, which could lead to resource exhaustion.
Also, EJBs might be moved between machines in a cluster and only managed resources can be moved along.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ClassType
[pmd-java:typeIs('java.lang.Thread') or pmd-java:typeIs('java.util.concurrent.ExecutorService')]
(: allow Thread.currentThread().getContextClassLoader() :)
[not(parent::TypeExpression[parent::MethodCall[pmd-java:matchesSig('_#currentThread()')
and parent::MethodCall[pmd-java:matchesSig('_#getContextClassLoader()')]
]
]
)]
(: allow Thread.onSpinWait() :)
[not(parent::TypeExpression[parent::MethodCall[pmd-java:matchesSig('_#onSpinWait()')]])]
(: exclude duplicated types on the same line :)
[not((parent::FieldDeclaration|parent::LocalVariableDeclaration)/VariableDeclarator/*[2][pmd-java:typeIs('java.lang.Thread') or pmd-java:typeIs('java.util.concurrent.ExecutorService')])
or
@BeginLine != (parent::FieldDeclaration|parent::LocalVariableDeclaration)/VariableDeclarator/ConstructorCall/ClassType/@BeginLine]
|
//MethodCall[*[1][not(pmd-java:nodeIs('MethodCall'))][pmd-java:nodeIs('Expression') and (pmd-java:typeIs('java.util.concurrent.Executors')
or pmd-java:typeIs('java.util.concurrent.ExecutorService'))]]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
// This is not allowed
public class UsingThread extends Thread {
}
// Neither this,
public class UsingExecutorService {
public void methodX() {
ExecutorService executorService = Executors.newFixedThreadPool(5);
}
}
// Nor this,
public class Example implements ExecutorService {
}
// Nor this,
public class Example extends AbstractExecutorService {
}
// Nor this
public class UsingExecutors {
public void methodX() {
Executors.newSingleThreadExecutor().submit(() -> System.out.println("Hello!"));
}
}
]]>
</example>
</rule>
<rule name="DontCallThreadRun"
language="java"
since="4.3"
message="Don't call Thread.run() explicitly, use Thread.start()"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_multithreading.html#dontcallthreadrun">
<description>
Explicitly calling Thread.run() method will execute in the caller's thread of control. Instead, call Thread.start() for the intended behavior.
</description>
<priority>4</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodCall[ pmd-java:matchesSig("java.lang.Thread#run()") ]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
Thread t = new Thread();
t.run(); // use t.start() instead
new Thread().run(); // same violation
]]>
</example>
</rule>
<rule name="DoubleCheckedLocking"
language="java"
since="1.04"
message="Double checked locking is not thread safe in Java."
class="net.sourceforge.pmd.lang.java.rule.multithreading.DoubleCheckedLockingRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_multithreading.html#doublecheckedlocking">
<description>
Partially created objects can be returned by the Double Checked Locking pattern when used in Java.
An optimizing JRE may assign a reference to the baz variable before it calls the constructor of the object the
reference points to.
Note: With Java 5, you can make Double checked locking work, if you declare the variable to be `volatile`.
For more details refer to: <http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html>
or <http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html>
</description>
<priority>1</priority>
<example>
<![CDATA[
public class Foo {
/*volatile */ Object baz = null; // fix for Java5 and later: volatile
Object bar() {
if (baz == null) { // baz may be non-null yet not fully created
synchronized(this) {
if (baz == null) {
baz = new Object();
}
}
}
return baz;
}
}
]]>
</example>
</rule>
<rule name="NonThreadSafeSingleton"
language="java"
since="3.4"
message="Singleton is not thread safe"
class="net.sourceforge.pmd.lang.java.rule.multithreading.NonThreadSafeSingletonRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_multithreading.html#nonthreadsafesingleton">
<description>
Creating singletons in a non-thread safe way leads to subtle, hard to reproduce concurrency issues:
A singleton might sometimes be created more than once (so it is not really a singleton anymore)
or calling code from a different thread might not see the singleton at all, or might see a non-null
reference to an object that is not fully constructed yet.
See Effective Java, 3rd edition, item 78: "Synchronize access to shared mutable data".
The rule property `checkNonStaticFields` is `false` by default, so that only
static fields are considered. This is the usual way to implement singletons. The rule finds methods
(regardless of whether they are static or non-static) that write to static fields after a null-check.
If the property is set to `true`, then additionally non-static fields are considered. This allows to
find lazy loading of instance fields.
Possible fixes for static singleton fields:
* Avoid lazy initialization if possible and instantiate the object directly, e.g.
`private static final Foo INSTANCE = new Foo();`. Lazy initialization is an optimization you should only
use if you have measured a performance gain (see Effective Java, 3rd edition, item 83: "Use lazy initialization
judiciously").
* Synchronize the entire method; for static fields, it must be a `static synchronized` method.
* Use an [initialize-on-demand holder class](https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom).
This is safe because the JVM initializes the holder class only once, on first access.
* Use an enum with a single item (see Effective Java, 3rd edition, item 3: "Enforce the singleton property with
a private constructor or an enum type"). This is not possible, if the singleton has to extend a class other
than `Enum` (interfaces are possible).
* Use `AtomicReference` with `compareAndSet` if a duplicate computation is acceptable.
Possible fixes for lazily initialized instance fields:
* Synchronize the entire method.
* Use `AtomicReference` with `compareAndSet` if a duplicate computation is acceptable.
* Use the double-checked locking pattern. The field must be declared `volatile`; without it,
the Java Memory Model doesn't guarantee that other threads see a fully constructed object.
Note that this only works on Java 5 and later.
(also possible for static fields, though the holder idiom is usually preferable)
[Reference](http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html)
</description>
<priority>3</priority>
<example>
<![CDATA[
private static Foo foo = null;
// multiple simultaneous callers may see partially initialized objects
public static Foo getInstance() {
if (foo == null) {
foo = new Foo();
}
return foo;
}
]]>
</example>
</rule>
<rule name="OverridingThreadRun"
language="java"
since="7.24.0"
message="Don''t override Thread.run() method, use Runnable instead"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_multithreading.html#overridingthreadrun">
<description>
Overriding `Thread::run` method is not recommended. Instead, implement `Runnable`
and pass an instance to the thread constructor. Using `Runnable` to represent a task
makes it more reusable and allows your class to extend another class.
When you use lambdas, this also allows you to write more concise code,
e.g. `new Thread(() -> System.out.println("Hello!")).start();`.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//(AnonymousClassDeclaration|ClassDeclaration)[ pmd-java:typeIs('java.lang.Thread') ]/ClassBody
/MethodDeclaration[@Name="run"][FormalParameters/@Size=0]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class GreetingThread extends Thread {
@Override
public void run() {
System.out.println("Hello!");
}
}
new GreetingThread().start(); // not recommended, use Runnable instead
public class GreetingRunnable implements Runnable {
@Override
public void run() {
System.out.println("Hello!");
}
}
new Thread(new GreetingRunnable()).start(); // preferred
]]>
</example>
</rule>
<rule name="UnsynchronizedStaticFormatter"
language="java"
since="6.11.0"
message="Static Formatter objects should be accessed in a synchronized manner"
class="net.sourceforge.pmd.lang.java.rule.multithreading.UnsynchronizedStaticFormatterRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_multithreading.html#unsynchronizedstaticformatter">
<description>
Instances of `java.text.Format` are generally not synchronized.
Sun recommends using separate format instances for each thread.
If multiple threads must access a static formatter, the formatter must be
synchronized on block level.
</description>
<priority>3</priority>
<example>
<![CDATA[
public class Foo {
private static final SimpleDateFormat sdf = new SimpleDateFormat();
void bar() {
sdf.format(); // poor, no thread-safety
}
void foo() {
synchronized (sdf) { // preferred
sdf.format();
}
}
}
]]>
</example>
</rule>
<rule name="UseConcurrentHashMap"
language="java"
minimumLanguageVersion="1.5"
since="4.2.6"
message="If you run in Java5 or newer and have concurrent access, you should use the ConcurrentHashMap implementation"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_multithreading.html#useconcurrenthashmap">
<description>
Since Java5 brought a new implementation of the Map designed for multi-threaded access, you can
perform efficient map reads without blocking other threads.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//VariableDeclarator[VariableId[pmd-java:typeIsExactly('java.util.Map')] and *[2][self::ConstructorCall and not(pmd-java:typeIs('java.util.concurrent.ConcurrentHashMap'))]]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class ConcurrentApp {
public void getMyInstance() {
Map map1 = new HashMap(); // fine for single-threaded access
Map map2 = new ConcurrentHashMap(); // preferred for use with multiple threads
// the following case will be ignored by this rule
Map map3 = someModule.methodThatReturnMap(); // might be OK, if the returned map is already thread-safe
}
}
]]>
</example>
</rule>
<rule name="UseNotifyAllInsteadOfNotify"
language="java"
since="3.0"
message="Call Thread.notifyAll() rather than Thread.notify()"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_multithreading.html#usenotifyallinsteadofnotify">
<description>
Thread.notify() awakens a thread monitoring the object. If more than one thread is monitoring, then only
one is chosen. The thread chosen is arbitrary; thus it's usually safer to call notifyAll() instead.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodCall[@MethodName="notify" and ArgumentList[count(*) = 0]]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
void bar() {
x.notify();
// If many threads are monitoring x, only one (and you won't know which) will be notified.
// use instead:
x.notifyAll();
}
]]>
</example>
</rule>
</ruleset>