Code that uses synchronization can sometimes be enigmatic and tricky to debug. Misuse of synchronization primitives is a common source of implementation errors. The analysis of the JDK 1.6.0 source code unveiled 31 bugs that fell into this category. \[[Pugh 08|AA. Java References#Pugh 08]\] Wiki Markup
...
of 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.
Noncompliant Code Example (Boolean
Lock Object)
This noncompliant code example synchronizes on a Boolean
lock object.
Code Block | ||
---|---|---|
| ||
private final Boolean initialized = Boolean.FALSE;
public void doSomething() {
synchronized (initialized) {
// ...
}
}
|
The 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 non-final object that is declared public
. It is possible that untrusted code can change the value of the lock object and foil the attempt to synchronize. boxed Integer
object.
Code Block | ||
---|---|---|
| ||
public Object publicLock = new Object();
synchronized(publicLock) {
// body
}
|
Compliant Solution
private int count = 0;
private final Integer Lock = count; // Boxed primitive Lock is shared
public void doSomething() {
synchronized (Lock) {
count++;
// ...
}
}
|
Boxed types may use the same instance for a range of integer values; consequently, they suffer from the same reuse problem as Boolean
constants. The wrapper object are reused when the value can be represented as a byte; 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)
) are unique and not reused. In general, locks on any data type that contains a boxed value are insecure.
Compliant Solution (Integer)
This compliant solution locks on a nonboxed Integer
, using a variant of the private lock object idiom. The doSomething()
method synchronizes using the intrinsic lock of the Integer
instance, Lock
This compliant solution synchronized on a private
object and is safe from malicious manipulation.
Code Block | ||
---|---|---|
| ||
private int count = 0; private final ObjectInteger privateLockLock = new ObjectInteger(count); public void doSomething() { synchronized (privateLockLock) { count++; // body... } } |
When explicitly constructed, an Integer
object has a unique reference and its own intrinsic lock that is distinct not only from other Integer
objects, but also from boxed integers that have the same value. While this is an acceptable solution, it can cause maintenance problems because developers can incorrectly assume that boxed integers are also appropriate lock objects. A more appropriate solution is to synchronize on a private final lock object as described 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 class java.lang.String
documentation [API 2006] A {{String}} constant is interned in Java. According to \[[API 06|AA. Java References#API 06]\] Class {{String}} documentation: Wiki Markup
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, a an interned String
constant object behaves like a global variable in the JVM. As demonstrated in this noncompliant code example, even if each when every instance of an object maintains its own lock
field lock
, it points , the fields all refer to a common String
constant in the JVM. Legitimate code that locks on the same String
constant will render all synchronization attempts inadequate. Likewise. Locking on String
constants has the same reuse problem as locking on Boolean
constants.
Additionally, hostile code from any other package can deliberately 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 | ||
---|---|---|
| ||
// thisThis bug was found in jetty-6.1.3 BoundedThreadPool private final String _lock = "oneLOCK"; synchronized(_lock public void doSomething() { /* ... */ } |
Noncompliant Code Example
This noncompliant code example synchronizes on a mutable field instead of an object and is bound to demonstrate no mutual exclusion properties, whatsoever. This is because the thread that holds a lock on the field can modify the referenced object's value which in turn allows another thread that is blocked on the unmodified value to resume, at the same time, granting access to a third thread that is blocked on the modified value. When aiming to modify a field, it is incorrect to synchronize on the same (or another) field as this is equivalent to synchronizing on the field's contents.
Code Block | ||
---|---|---|
| ||
private Integer semaphore = new Integer(0);
synchronized(semaphore) { /* ... */ }
|
This is a mutual exclusion problem as opposed to the sharing issue discussed in the previous noncompliant code example. Note that only the boxed Integer
primitive is shared as shown below and not the Integer
object (new Integer(value)
) itself.
Code Block |
---|
int lock = 0;
Integer Lock = lock; // boxed primitive Lock will be shared
|
In general, holding a lock on any data structure that contains a boxed value can be dangerous.
Compliant Solution
synchronized (lock) {
// ...
}
}
|
String
literals are constant and are automatically interned. Consequently, 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
instanceIn the absence of an existing object to lock on, using a raw object to synchronize suffices.
Code Block | ||
---|---|---|
| ||
private final ObjectString lock = new ObjectString("LOCK"); public void doSomething() { synchronized (lock) { /*/ ... */ } |
Note that the instance of the raw object should not be changed from within the synchronized block. For example, creating and storing the reference of a new object into the lock
field.
Noncompliant Code Example
Synchronizing on getClass()
rather than a class literal can also be counterproductive. Whenever the implementing class is subclassed, the subclass will end up locking on a completely different Class
object.
Code Block | ||
---|---|---|
| ||
synchronized(getClass()) { /* ... */ }
|
Wiki Markup |
---|
This idea is sometimes easy to miss, especially when the Java Language Specification is misunderstood. Section 4.3.2 "The Class Object" of the 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 it is required to synchronize on the Class
object.
Compliant Solution
Explicitly define the name of the class (superclass in this example) in the synchronization block. This can be achieved in two ways. One way is to explicitly pass the superclass's instance.
Code Block | ||
---|---|---|
| ||
synchronized(SuperclassName.class) { ... }
|
The second way is to use the Class.forName()
method.
Code Block | ||
---|---|---|
| ||
synchronized(Class.forName("SuperclassName")) { ... }
|
Finally, it is more important to recognize the entities with whom synchronization is required rather than indiscreetly scavenging for variables or objects to synchronize on.
Noncompliant Code Example
Wiki Markup |
---|
When using synchronization wrappers, the synchronization object must be the {{Collection}} object. The synchronization is necessary to enforce atomicity ([CON38-J. Ensure atomicity of thread-safe code]). This noncompliant code example demonstrates inappropriate synchronization resulting from locking on a {{Collection}} view instead of the Collection itself \[[Tutorials 08|AA. Java References#Tutorials 08]\]. |
Code Block | ||
---|---|---|
| ||
Map<Integer, String> m = Collections.synchronizedMap(new HashMap<Integer, String>());
Set<Integer> s = m.keySet();
synchronized(s) { // Incorrectly synchronizes on s
for(Integer k : s) { /* do something */ }
}
|
Compliant Solution
This compliant solution correctly synchronizes on the Collection
object instead of the Collection
view.
Code Block | ||
---|---|---|
| ||
// ...
synchronized(m) { // Synchronize on m, not s
for(Integer k : s) { /* do something */ }
}
|
Noncompliant Code Example
This noncompliant code example incorrectly uses a ReentrantLock
as the lock object.
Code Block | ||
---|---|---|
| ||
final Lock lock = new ReentrantLock();
synchronized(lock) { /* do something */ }
|
Compliant Solution
The proper mechanism to lock in this case is to explicitly use the lock()
and unlock()
methods provided by the ReentrantLock
class.
Code Block | ||
---|---|---|
| ||
final Lock lock = new ReentrantLock();
lock.lock();
try {
// ...
} finally {
lock.unlock();
}
|
Risk Assessment
}
|
A String
instance differs from a String
literal. The instance has a unique reference and its own intrinsic lock that is distinct from other String
object instances or literals. Nevertheless, a better approach is to 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 lock = new Object();
public void doSomething() {
synchronized (lock) {
// ...
}
}
|
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 incorrect variable can provide a false sense of thread safety and result in nondeterministic behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|
LCK01-J | medium | probable | medium | P8 | L2 |
Automated Detection
TODO
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
\[[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] |
Some static analysis tools can detect violations of this 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 | |
...
CON35-J. Do not try to force thread shutdown 09. Concurrency (CON) CON37-J. Never apply a lock to methods making network calls