Movatterモバイル変換


[0]ホーム

URL:


 
» Multithreading Edit on GitHub

Multithreading

Rules that flag issues when dealing with multiple threads of execution.
Table of Contents

AvoidSynchronizedAtMethodLevel

Since: PMD 3.0

Priority: Medium (3)

Method-level synchronization will pin virtual threads and can cause performance problems. Additionally, it can causeproblems when new code is added to the method. Block-level ReentrantLock helps to ensure that only the code thatneeds mutual exclusion will be locked.

This rule is defined by the following XPath expression:

//MethodDeclaration[pmd-java:modifiers()="synchronized"]

Example(s):

publicclassFoo{// Try to avoid this:synchronizedvoidfoo(){// code, that doesn't need synchronization// ...// code, that requires synchronizationif(!sharedData.has("bar")){sharedData.add("bar");}// more code, that doesn't need synchronization// ...}// Prefer this:LockinstanceLock=newReentrantLock();voidbar(){// code, that doesn't need synchronization// ...try{instanceLock.lock();// or instanceLock.tryLock(long time, TimeUnit unit)if(!sharedData.has("bar")){sharedData.add("bar");}}finally{instanceLock.unlock();}// more code, that doesn't need synchronization// ...}// Try to avoid this for static methods:staticsynchronizedvoidfooStatic(){}// Prefer this:privatestaticLockCLASS_LOCK=newReentrantLock();staticvoidbarStatic(){// code, that doesn't need synchronization// ...try{CLASS_LOCK.lock();// code, that requires synchronization}finally{CLASS_LOCK.unlock();}// more code, that doesn't need synchronization// ...}}

Use this rule by referencing it:

<ruleref="category/java/multithreading.xml/AvoidSynchronizedAtMethodLevel"/>

AvoidSynchronizedStatement

Since: PMD 7.5.0

Priority: Medium (3)

Synchronization will pin virtual threads and can cause performance problems.

This rule is defined by the following XPath expression:

//SynchronizedStatement

Example(s):

publicclassFoo{// Try to avoid this:voidfoo(){// code that doesn't need mutual exclusionsynchronized(this){// code that requires mutual exclusion}// more code that doesn't need mutual exclusion}// Prefer this:LockinstanceLock=newReentrantLock();voidfoo(){// code that doesn't need mutual exclusiontry{instanceLock.lock();// or instanceLock.tryLock(long time, TimeUnit unit)// code that requires mutual exclusion}finally{instanceLock.unlock();}// more code that doesn't need mutual exclusion}}

Use this rule by referencing it:

<ruleref="category/java/multithreading.xml/AvoidSynchronizedStatement"/>

AvoidThreadGroup

Since: PMD 3.6

Priority: Medium (3)

Avoid using java.lang.ThreadGroup; although it is intended to be used in a threaded environmentit contains methods that are not thread-safe.

This rule is defined by the following XPath expression:

//ConstructorCall/ClassType[pmd-java:typeIs('java.lang.ThreadGroup')]|//MethodCall[@MethodName='getThreadGroup']

Example(s):

publicclassBar{voidbuz(){ThreadGrouptg=newThreadGroup("My threadgroup");tg=newThreadGroup(tg,"my thread group");tg=Thread.currentThread().getThreadGroup();tg=System.getSecurityManager().getThreadGroup();}}

Use this rule by referencing it:

<ruleref="category/java/multithreading.xml/AvoidThreadGroup"/>

AvoidUsingVolatile

Since: PMD 4.1

Priority: Medium High (2)

Use of the keyword ‘volatile’ is generally used to fine tune a Java application, and therefore, requiresa good expertise of the Java Memory Model. Moreover, its range of action is somewhat misknown. Therefore,the volatile keyword should not be used for maintenance purpose and portability.

This rule is defined by the following XPath expression:

//FieldDeclaration[pmd-java:modifiers()="volatile"]

Example(s):

publicclassThrDeux{privatevolatileStringvar1;// not suggestedprivateStringvar2;// preferred}

Use this rule by referencing it:

<ruleref="category/java/multithreading.xml/AvoidUsingVolatile"/>

DoNotUseThreads

Since: PMD 4.1

Priority: Medium (3)

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.

This rule is defined by the following XPath expression:

//ClassType[pmd-java:typeIs('java.lang.Thread')orpmd-java:typeIs('java.util.concurrent.ExecutorService')](: allow Thread.currentThread().getContextClassLoader() :)[not(parent::TypeExpression[parent::MethodCall[pmd-java:matchesSig('_#currentThread()')andparent::MethodCall[pmd-java:matchesSig('_#getContextClassLoader()')]]])](: exclude duplicated types on the same line :)[not((parent::FieldDeclaration|parent::LocalVariableDeclaration)/VariableDeclarator/*[2][pmd-java:typeIs('java.lang.Thread')orpmd-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')orpmd-java:typeIs('java.util.concurrent.ExecutorService'))]]

Example(s):

// This is not allowedpublicclassUsingThreadextendsThread{}// Neither this,publicclassUsingExecutorService{publicvoidmethodX(){ExecutorServiceexecutorService=Executors.newFixedThreadPool(5);}}// Nor this,publicclassExampleimplementsExecutorService{}// Nor this,publicclassExampleextendsAbstractExecutorService{}// Nor thispublicclassUsingExecutors{publicvoidmethodX(){Executors.newSingleThreadExecutor().submit(()->System.out.println("Hello!"));}}

Use this rule by referencing it:

<ruleref="category/java/multithreading.xml/DoNotUseThreads"/>

DontCallThreadRun

Since: PMD 4.3

Priority: Medium Low (4)

Explicitly calling Thread.run() method will execute in the caller’s thread of control. Instead, call Thread.start() for the intended behavior.

This rule is defined by the following XPath expression:

//MethodCall[pmd-java:matchesSig("java.lang.Thread#run()")]

Example(s):

Threadt=newThread();t.run();// use t.start() insteadnewThread().run();// same violation

Use this rule by referencing it:

<ruleref="category/java/multithreading.xml/DontCallThreadRun"/>

DoubleCheckedLocking

Since: PMD 1.04

Priority: High (1)

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 thereference points to.

Note: With Java 5, you can make Double checked locking work, if you declare the variable to bevolatile.

For more details refer to:http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.htmlorhttp://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.multithreading.DoubleCheckedLockingRule

Example(s):

publicclassFoo{/*volatile */Objectbaz=null;// fix for Java5 and later: volatileObjectbar(){if(baz==null){// baz may be non-null yet not fully createdsynchronized(this){if(baz==null){baz=newObject();}}}returnbaz;}}

Use this rule by referencing it:

<ruleref="category/java/multithreading.xml/DoubleCheckedLocking"/>

NonThreadSafeSingleton

Since: PMD 3.4

Priority: Medium (3)

Non-thread safe singletons can result in bad state changes. Eliminatestatic singletons if possible by instantiating the object directly. Staticsingletons are usually not needed as only a single instance exists anyway.Other possible fixes are to synchronize the entire method or to use aninitialize-on-demand holder class.

Refrain from using the double-checked locking pattern. The Java Memory Model doesn’tguarantee it to work unless the variable is declared asvolatile, adding an uneededperformance penalty.Reference

See Effective Java, item 48.

This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.multithreading.NonThreadSafeSingletonRule

Example(s):

privatestaticFoofoo=null;//multiple simultaneous callers may see partially initialized objectspublicstaticFoogetFoo(){if(foo==null){foo=newFoo();}returnfoo;}

This rule has the following properties:

NameDefault ValueDescription
checkNonStaticMethodstrueCheck for non-static methods. Do not set this to false and checkNonStaticFields to true.
checkNonStaticFieldsfalseCheck for non-static fields. Do not set this to true and checkNonStaticMethods to false.

Use this rule with the default properties by just referencing it:

<ruleref="category/java/multithreading.xml/NonThreadSafeSingleton"/>

Use this rule and customize it:

<ruleref="category/java/multithreading.xml/NonThreadSafeSingleton"><properties><propertyname="checkNonStaticMethods"value="true"/><propertyname="checkNonStaticFields"value="false"/></properties></rule>

UnsynchronizedStaticFormatter

Since: PMD 6.11.0

Priority: Medium (3)

Instances ofjava.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 besynchronized on block level.

This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.multithreading.UnsynchronizedStaticFormatterRule

Example(s):

publicclassFoo{privatestaticfinalSimpleDateFormatsdf=newSimpleDateFormat();voidbar(){sdf.format();// poor, no thread-safety}voidfoo(){synchronized(sdf){// preferredsdf.format();}}}

This rule has the following properties:

NameDefault ValueDescription
allowMethodLevelSynchronizationfalseIf true, method level synchronization is allowed as well as synchronized block. Otherwise only synchronized blocks are allowed.

Use this rule with the default properties by just referencing it:

<ruleref="category/java/multithreading.xml/UnsynchronizedStaticFormatter"/>

Use this rule and customize it:

<ruleref="category/java/multithreading.xml/UnsynchronizedStaticFormatter"><properties><propertyname="allowMethodLevelSynchronization"value="false"/></properties></rule>

UseConcurrentHashMap

Since: PMD 4.2.6

Priority: Medium (3)

Minimum Language Version: Java 1.5

Since Java5 brought a new implementation of the Map designed for multi-threaded access, you canperform efficient map reads without blocking other threads.

This rule is defined by the following XPath expression:

//VariableDeclarator[VariableId[pmd-java:typeIsExactly('java.util.Map')]and*[2][self::ConstructorCallandnot(pmd-java:typeIs('java.util.concurrent.ConcurrentHashMap'))]]

Example(s):

publicclassConcurrentApp{publicvoidgetMyInstance(){Mapmap1=newHashMap();// fine for single-threaded accessMapmap2=newConcurrentHashMap();// preferred for use with multiple threads// the following case will be ignored by this ruleMapmap3=someModule.methodThatReturnMap();// might be OK, if the returned map is already thread-safe}}

Use this rule by referencing it:

<ruleref="category/java/multithreading.xml/UseConcurrentHashMap"/>

UseNotifyAllInsteadOfNotify

Since: PMD 3.0

Priority: Medium (3)

Thread.notify() awakens a thread monitoring the object. If more than one thread is monitoring, then onlyone is chosen. The thread chosen is arbitrary; thus it’s usually safer to call notifyAll() instead.

This rule is defined by the following XPath expression:

//MethodCall[@MethodName="notify"andArgumentList[count(*)=0]]

Example(s):

voidbar(){x.notify();// If many threads are monitoring x, only one (and you won't know which) will be notified.// use instead:x.notifyAll();}

Use this rule by referencing it:

<ruleref="category/java/multithreading.xml/UseNotifyAllInsteadOfNotify"/>

This documentation is written in markdown.
If there is something missing or can be improved, edit this page on github and create a PR: Edit on GitHub

©2025 PMD Open Source Project. All rights reserved.
Site last generated: Jun 27, 2025

PMD                logo


[8]ページ先頭

©2009-2025 Movatter.jp