Code that uses synchronization can sometimes be enigmatic and tricky to debug. Misuse of synchronization primitives is a common source of implementation errors. An analysis of the JDK 1.6.0 source code unveiled at least 31 bugs that fell into this category. [[Pugh 08]]
Noncompliant Code Example (nonfinal lock object)
This noncompliant code example locks on a nonfinal object that is declared public
. It is possible for untrusted code to change the value of the lock object and foil any attempts to synchronize.
public Object publicLock = new Object(); synchronized(publicLock) { // body }
Compliant Solution (final
lock object)
This compliant solution synchronizes on a private final
object and is safe from malicious manipulation.
private final Object privateLock = new Object(); synchronized(privateLock) { // body }
Noncompliant Code Example (String
constant)
A String
constant is interned in Java. According to the Java API [[API 06]] Class String
documentation:
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 String
constant behaves like a global variable in the JVM. As demonstrated in this noncompliant code 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 renders 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 locks on a boxed Integer
object.
int lock = 0; Integer Lock = lock; // Boxed primitive Lock will be shared synchronized(Lock) { /* ... */ }
Boxed types may use the same instance for a range of integer values and consequently, suffer from the same problems as String
constants. Note that the boxed Integer
primitive is shared and not the Integer
object (new Integer(value)
) itself. In general, holding a lock on any data structure that contains a boxed value is insecure.
Noncompliant Code Example (Mutable lock object)
This noncompliant code example synchronizes on a mutable, nonfinal field and demonstrates no mutual exclusion properties.
private Integer semaphore = new Integer(0); synchronized(semaphore) { /* ... */ }
This is because the thread that holds a lock on the nonfinal field object can modify the field's value, allowing another thread that is blocked on the unmodified value to resume, at the same time, contending for the lock with a third thread that is blocked on the modified value. It is insecure to synchronize on a mutable field because this is equivalent to synchronizing on the field's contents. This is a mutual exclusion problem as opposed to the sharing issue discussed in the previous noncompliant code example.
Compliant Solution (final
lock object)
This compliant solution synchronizes using a lock object that is declared as final
.
private final Integer semaphore = new Integer(0); synchronized(semaphore) { /* ... */ }
As long as the lock object is final
, it is acceptable for the referenced object to be mutable. In this compliant solution, the Integer
object happens to be immutable by definition.
Noncompliant Code Example (Boolean
lock object)
This noncompliant code example uses a Boolean
field to synchronize. However, there can only be two possible valid values (true
and false
) that a Boolean
can assume. Consequently, any other code that synchronizes on the same value can cause unresponsiveness and deadlocks [[Findbugs 08]].
private Boolean initialized = Boolean.FALSE; synchronized(initialized) { if (!initialized) { // Perform initialization initialized = Boolean.TRUE; } }
Compliant Solution (raw Object
lock object)
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 is highly inadvisable. To prevent such modifications, declare the lock
field as final
.
Noncompliant Code Example (getClass()
lock object)
Synchronizing on getClass()
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).
synchronized(getClass()) { /* ... */ }
Section 4.3.2 "The Class Object" of the specification [[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 can only synchronize on the Class
object of the base class.
Compliant Solution (1) (class name qualification)
Explicitly define the name of the class through name qualification (superclass in this example) in the synchronization block.
synchronized(SuperclassName.class) { // ... }
Compliant Solution (2) (Class.forName()
)
This compliant solution uses the Class.forName()
method to synchronize on the superclass's Class
object.
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 (collection view)
When using synchronization wrappers, the synchronization object must be the Collection
object. The synchronization is necessary to enforce atomicity ([CON07-J. Ensure atomicity of calls to thread-safe APIs]). This noncompliant code 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 (collection lock object)
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 (nonstatic lock object)
This noncompliant code example uses a nonstatic lock object to guard access to a static
field. If two Runnable
tasks, each consisting of a thread are started, they will create two instances of the lock object and lock on each separately. This does not prevent either thread from observing an inconsistent value of field counter
because the increment operation on volatile
fields is not atomic, in the absence of proper synchronization.
class CountBoxes implements Runnable { static volatile int counter; // ... Object lock = new Object(); public void run() { synchronized(lock) { counter++; // ... } } public static void main(String[] args) { Runnable r1 = new CountBoxes(); Thread t1 = new Thread(r1); Runnable r2 = new CountBoxes(); Thread t2 = new Thread(r2); t1.start(); t2.start(); } }
Compliant Solution (static
lock object)
This compliant solution declares the lock object as static
and consequently, ensures the atomicity of the increment operation.
class CountBoxes implements Runnable { static volatile int counter; // ... static Object lock = new Object(); // ... }
Noncompliant Code Example (ReentrantLock
lock object)
This noncompliant code example incorrectly uses a ReentrantLock
as the lock object.
final Lock lock = new ReentrantLock(); synchronized(lock) { /* ... */ }
Compliant Solution (lock()
and unlock()
)
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 |
---|---|---|---|---|---|
CON02- 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
VOID CON00-J. Synchronize access to shared mutable variables 11. Concurrency (CON) CON03-J. Do not use background threads during class initialization