Misuse of synchronization primitives is a common source of implementation errors. Most concurrency vulnerabilities arise from locking on the wrong kind of object. An analysis of the JDK 1.6.0 source code unveiled at least 31 bugs that fell into this category \[[Pugh 08|AA. Java References#Pugh 08]\]. It is important to recognize the entities with whom synchronization is required rather than indiscreetly scavenging for variables or objects to synchronize onof concurrency issues. Synchronizing on objects that may be reused can result in deadlock and nondeterministic behavior. Consequently, programs must never synchronize on objects that may be reused. Wiki Markup
Noncompliant Code Example (Boolean
...
Lock Object)
This noncompliant code example uses synchronizes on a Boolean
field for synchronization lock object.
Code Block | ||
---|---|---|
| ||
private final Boolean initialized = Boolean.FALSE; public void doSomething() { synchronized (initialized) { // ... } } |
There can only be two possible valid values ({{true}} and {{false}}, discounting {{null}}) that {{initialized}} can assume. Consequently, any other code that synchronizes on a {{Boolean}} variable with the same value, may induce unresponsiveness and deadlocks \[[Findbugs 08|AA. Java References#Findbugs 08]\]. The Wiki Markup Boolean
type is unsuitable for locking purposes because it allows only two values: true and false. Boolean literals containing the same value share unique instances of the Boolean
class in the Java Virtual Machine (JVM). In this example, initialized
refers to the instance corresponding to the value Boolean.FALSE
. If any other code were to inadvertently synchronize on a Boolean
literal with this value, the lock instance would be reused and the system could become unresponsive or could deadlock.
Noncompliant Code Example (Boxed
...
Primitive)
This noncompliant code example locks on a boxed Integer
object.
Code Block | ||
---|---|---|
| ||
private int lockcount = 0; private final Integer Lock = lockcount; // Boxed primitive Lock will beis shared public void doSomething() { synchronized (Lock) { count++; // ... } } |
Boxed types are allowed to may use the same instance for a range of integer values and ; consequently, they suffer from the same reuse problem as Boolean
constants. If the primitive The wrapper object are reused when the value can be represented as a byte, the wrapper object is reused. Note that the boxed Integer
primitive is shared and not the Integer
object ; JVM implementations are also permitted to reuse wrapper objects for larger ranges of values. While use of the intrinsic lock associated with the boxed Integer
wrapper object is insecure; instances of the Integer
object constructed using the new
operator (new Integer(value)
) itselfare unique and not reused. In general, holding a lock locks on any data type that contains a boxed value is are insecure.
Compliant Solution (Integer)
This compliant solution locks on a non-boxed Integera nonboxed Integer
, using a variant of the private lock object idiom. The doSomething()
method synchronizes using the intrinsic lock of the Integer
instance, Lock
.
Code Block | ||
---|---|---|
| ||
private int lockcount = 0; private final Integer Lock = new Integer(lockcount); public void doSomething() { synchronized (Lock) { count++; // ... } } |
When explicitly constructed, an Integer
object has a unique reference and its own intrinsic lock that is distinct not shared with only from other Integer
objects or , but also from boxed integers having that have the same value. While this is an acceptable solution, it may can cause maintenance problems . It is always better because developers can incorrectly assume that boxed integers are also appropriate lock objects. A more appropriate solution is to synchronize on a private final raw Object
lock object as described next.
Compliant Solution (private final internal raw Object
)
This compliant solution uses an internal private final lock object. This is one of the few cases where a raw Object
is useful.
Code Block | ||
---|---|---|
| ||
private final Object lock = new Object();
public void doSomething() {
synchronized(lock) {
// ...
}
}
|
For more information on using an Object
as a lock, see CON04-J. Synchronize using an internal private final lock object.
in the final compliant solution for this rule.
Noncompliant Code Example (Interned String
Object
...
)
This noncompliant code example locks on an interned String
object.
Code Block | ||
---|---|---|
| ||
private final String _lock = new String("LOCK").intern(); public void doSomething() { synchronized (_lock) { // ... } } |
...
According to the Java API \[[ API 06|AA. Java References#API 06]\], class {{java.lang.String
}} documentation documentation [API 2006]:
When the
intern()
method is invoked, if the pool already contains a string equal to thisString
object as determined by theequals(Object)
method, then the string from the pool is returned. Otherwise, thisString
object is added to the pool and a reference to thisString
object is returned.
Consequently, an interned String
object behaves like a global variable in the JVM. As demonstrated in this noncompliant code example, even if when every instance of an object maintains its own lock
field lock
, the field points fields all refer to a common String
constant in the JVM. Trusted code that locks on the same String
constant renders all synchronization attempts inadequate. Similarly. Locking on String
constants has the same reuse problem as locking on Boolean
constants.
Additionally, hostile code from any other package can exploit this vulnerability, if the class is accessible. See rule LCK00-J. Use private final lock objects to synchronize classes that may interact with untrusted code for more information.
Noncompliant Code Example (String
...
Literal)
This noncompliant code example locks on a final String
literal.
Code Block | ||
---|---|---|
| ||
// This bug was found in jetty-6.1.3 BoundedThreadPool private final String _lock = "LOCK"; // ...public void doSomething() { synchronized (_lock) { // ... } // ...} |
A String
literal is a literals are constant and is are automatically interned. Consequently, it this example suffers from the same pitfalls as the preceding noncompliant code example.
Compliant Solution (String
...
Instance)
This compliant solution locks on a noninterned String
instance that is not interned.
Code Block | ||
---|---|---|
| ||
private final String _lock = new String("LOCK"); public void doSomething() { synchronized (_lock) { // ... } } |
A String
instance differs from a String
literal. The instance has a unique reference and its own intrinsic lock that is not shared by other string objects distinct from other String
object instances or literals. A more suitable Nevertheless, a better approach is to use the private final internal raw Object
discussed earlier.
Noncompliant Code Example (getClass()
lock object)
Synchronizing on return values of the Object.getClass()
method, rather than a class literal can also be counterproductive. Whenever the implementing class is subclassed, the subclass locks on a completely different Class
object (subclass's type).
Code Block | ||
---|---|---|
| ||
public void doSomething() {
synchronized(getClass()) {
// ...
}
}
|
Wiki Markup |
---|
Section 4.3.2 "The Class Object" of the Java Language specification \[[JLS 05|AA. Java References#JLS 05]\] describes how method synchronization works: |
A class method that is declared
synchronized
synchronizes on the lock associated with theClass
object of the class.
This does not mean that a subclass using getClass()
can only synchronize on the Class
object of the base class. In fact, it will lock on its own Class
object, which may or may not be what the programmer had in mind. The intent should be appropriately documented or annotated.
Compliant Solution (class name qualification)
Explicitly define the name of the class through name qualification (superclass in this compliant solution) in the synchronized block.
Code Block | ||
---|---|---|
| ||
public void doSomething() {
synchronized(SuperclassName.class) {
// ...
}
}
|
The class object being synchronized should not be accessible to hostile code. If the class is package-private, then external packages may not access the Class object, ensuring its trustworthiness as an intrinsic lock object. For more information, see CON04-J. Synchronize using an internal private final lock object.
Compliant Solution (Class.forName()
)
This compliant solution uses the Class.forName()
method to synchronize on the superclass's Class
object.
Code Block | ||
---|---|---|
| ||
public void doSomething() {
synchronized(Class.forName("SuperclassName")) {
// ...
}
}
|
The class object being synchronized should not be accessible to hostile code, as discussed in the previous compliant solution. Furthermore, care must be taken so that untrusted inputs are not accepted as arguments while loading classes using Class.forname()
(see SEC05-J. Do not expose standard APIs that use the immediate caller's class loader instance to untrusted code for more information).
Noncompliant Code Example (ReentrantLock
lock object)
This noncompliant code example incorrectly uses a ReentrantLock
as the lock object.
Code Block | ||
---|---|---|
| ||
private final Lock lock = new ReentrantLock();
public void doSomething() {
synchronized(lock) {
// ...
}
}
|
Similarly, 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 intrinsic locks of these classes is a questionable practice even though the code may appear to function correctly. This problem usually comes up in practice when refactoring from intrinsic locking to the java.util.concurrent
dynamic locking utilities.
Compliant Solution (lock()
and unlock()
)
Instead of using the intrinsic locks of objects that implement the Lock
interface, including ReentrantLock
, use the lock()
and unlock()
methods provided by the Lock
interface.
synchronize on a private final lock object, as shown in the following compliant solution.
Compliant Solution (Private Final Lock Object
)
This compliant solution synchronizes on a private final lock object. This is one of the few cases in which a java.lang.Object
instance is useful.
Code Block | ||
---|---|---|
| ||
private final Object | ||
Code Block | ||
| ||
private final Lock lock = new ReentrantLockObject(); public void doSomething() { synchronized (lock.lock(); try { // ... } finally { lock.unlock(); } } |
If there is no real need of 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.
Noncompliant Code Example (collection view)
This noncompliant code example synchronizes on the view of a synchronized map.
Code Block | ||
---|---|---|
| ||
private final Map<Integer, String> map = Collections.synchronizedMap(new HashMap<Integer, String>());
private final Set<Integer> set = map.keySet();
public void doSomething() {
synchronized(set) { // Incorrectly synchronizes on set
for(Integer k : set) {
// ...
}
}
}
|
Wiki Markup |
---|
When using synchronization wrappers, the synchronization object must be the {{Collection}} object. The synchronization is necessary to enforce atomicity ([CON07-J. Do not assume that a grouping of calls to independently atomic methods is atomic]). This noncompliant code example demonstrates inappropriate synchronization resulting from locking on a Collection view instead of the Collection object itself \[[Tutorials 08|AA. Java References#Tutorials 08]\]. |
Wiki Markup |
---|
The {{java.util.Collections}} interfaces' documentation \[[API 06|AA. Java References#API 06]\] states: |
It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views... Failure to follow this advice may result in non-deterministic behavior.
Compliant Solution (collection lock object)
This compliant solution correctly synchronizes on the Collection
object instead of the Collection
view.
Code Block | ||
---|---|---|
| ||
// ...
Map<Integer, String> map = Collections.synchronizedMap(new HashMap<Integer, String>());
public void doSomething() {
synchronized(map) { // Synchronize on map, not set
for(Integer k : map) {
// ...
}
}
}
|
Risk Assessment
For more information on using an Object
as a lock, see rule LCK00-J. Use private final lock objects to synchronize classes that may interact with untrusted code.
Risk Assessment
A significant number of concurrency vulnerabilities arise from locking on the wrong kind of object. It is important to consider the properties of the lock object rather than simply scavenging for objects on which to synchronizeSynchronizing on an inappropriate object can provide a false sense of thread safety and result in non-deterministic behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|
LCK01-J | medium | probable | medium | P8 | L2 |
Automated Detection
Currently, SureLogic Flashlight does not detect all Some static analysis tools can detect violations of this guideline. It detects:
Noncompliant Code Example | Message |
---|
It does not detect:
Noncompliant Code Example | Message |
---|---|
| No obvious issues |
Boxed primitive | No obvious issues |
interned | No obvious issues |
String literal | No data available about field accesses |
| No data available about field accesses |
| No obvious issues |
Collection view | No obvious issues |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] Class String, Collections
\[[Pugh 08|AA. Java References#Pugh 08]\] "Synchronization"
\[[Miller 09|AA. Java References#Miller 09]\] Locking
\[[Tutorials 08|AA. Java References#Tutorials 08]\] [Wrapper Implementations|http://java.sun.com/docs/books/tutorial/collections/implementations/wrapper.html] |
rule.
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
The Checker Framework |
| Lock Checker | Concurrency and lock errors (see Chapter 6) | ||||||
Parasoft Jtest |
| CERT.LCK01.SCS | Do not synchronize on constant Strings | ||||||
PVS-Studio |
| V6070 | |||||||
SonarQube |
| S1860 | |||||||
ThreadSafe |
| CCE_CC_REUSEDOBJ_SYNC | Implemented |
Bibliography
[API 2006] | Class String, Collections |
Locking | |
Synchronization | |
...
VOID CON00-J. Synchronize access to shared mutable variables 11. Concurrency (CON) CON03-J. Do not use background threads during class initialization