It is inappropriate to lock on an object of a class that implements either the Lock
or Condition
interface (or both) of package java.util.concurrent.locks
. Using the intrinsic locks of these classes is a questionable practice even though the code may appear to function correctly. This problem is commonly discovered when code is refactored from intrinsic locking to the java.util.concurrent
dynamic locking utilities.
Noncompliant Code Example (ReentrantLock
lock object)
The doSomething()
method in this noncompliant code example synchronizes on the the intrinsic lock of an instance of ReentrantLock
instead of the reentrant mutual exclusion Lock
encapsulated by ReentrantLock
.
private final Lock lock = new ReentrantLock(); public void doSomething() { synchronized(lock) { // ... } }
Compliant Solution (lock()
and unlock()
)
Instead of using the intrinsic locks of objects that implement the Lock
interface, such as ReentrantLock
, use the lock()
and unlock()
methods provided by the Lock
interface.
private final Lock lock = new ReentrantLock(); public void doSomething() { lock.lock(); try { // ... } finally { lock.unlock(); } }
If there is no requirement for using the advanced functionality of the dynamic locking utilities of package java.util.concurrent
, prefer using the Executor
framework or other concurrency primitives such as synchronization and atomic classes.
Risk Assessment
Synchronizing on the intrinsic lock of high level concurrency utilities can cause non-deterministic behavior because the class may end up with two different locking policies.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
CON39- J |
medium |
probable |
medium |
P8 |
L2 |
Automated Detection
The following table summarizes the examples flagged as violations by FindBugs:
Noncompliant Code Example |
Flagged |
Checker |
Message |
---|---|---|---|
|
No |
n/a |
n/a |
The following table summarizes the examples flagged as violations by SureLogic Flashlight:
Noncompliant Code Example |
Flagged |
Message |
---|---|---|
|
No |
No obvious issues |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
TODO check references
[[API 06]]
[[Findbugs 08]].
[[Pugh 08]] "Synchronization"
[[Miller 09]] Locking
[[Tutorials 08]] Wrapper Implementations
[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_left.png!] [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_up.png!] [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_right.png!]