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]]
Noncompliant Code Example
A String
constant is interned in Java. According to [[API 06]] Class String
documentation:
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
Thus a String
constant behaves like a global variable in the JVM. As demonstrated in this noncompliant example, even if each instance of an object maintains its own field lock
, it points to a common String
constant in the JVM. Legitimate code that locks on the same String constant will render all synchronization attempts inadequate. Likewise, hostile code from any other package can deliberately exploit this vulnerability.
// this bug was found in jetty-6.1.3 BoundedThreadPool private final String _lock = "one"; synchronized(_lock) { ... }
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 will allow another thread that is blocked on the old 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.
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 example. Note that only the boxed Integer
primitive is shared as shown below and not the Integer
object (new Integer(value)
) itself.
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
In the absence of an existing object to lock on, using a raw object to synchronize suffices.
private final Object lock = new Object(); 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.
synchronized(getClass()) { ... }
This idea is sometimes easy to miss, especially when one goes by the Java Language Specification [[JLS 05]] section 4.3.2 "The Class Object", that describes how method synchronization works:
A class method that is declared synchronized synchronizes on the lock associated with the Class object of the class.
Compliant Solution
Explicitly define the name of the class (superclass here) in the synchronization block. This can be achieved in two ways. Onw way is to explicitly pass the superclass's instance.Class.forName()
.
synchronized(SuperclassName.class) { ... }
The second way is to use the Class.forName()
method.
synchronized(Class.forName("SuperclassName")) { ... }
Finally, it is important to recognize the entities with which synchronization is required rather than indiscreetly scavenging for variables or objects to synchronize on.
Noncompliant Code Example
When using synchronization wrappers, the synchronization object needs to be the Collection
object. The synchronization is necessary to enforce atomicity ([CON38-J. Ensure atomicity of thread-safe code]). This noncompliant example demonstrates inappropriate synchronization resulting from locking on a Collection
view instead of the Collection itself [[Tutorials 08]].
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.
// ... synchronized(m) { // Synchronize on m, not s for(Integer k : s) { /* do something */ } }
Noncompliant Code Example
This noncompliant example incorrectly uses a ReentrantLock
as the lock object.
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.
final Lock lock = new ReentrantLock(); lock.lock(); try { // ... } finally { lock.unlock(); }
Risk Assessment
Synchronizing on an incorrect variable can provide a false sense of thread safety and result in nondeterministic behavior.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
CON36-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
[[API 06]] Class String
[[Pugh 08]] "Synchronization"
[[Miller 09]] Locking
[[Tutorials 08]] Wrapper Implementations
CON35-J. Do not try to force thread shutdown 08. Concurrency (CON) 08. Concurrency (CON)