You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 70 Next »

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 (Boolean lock object)

This noncompliant code example uses a Boolean field for synchronization.

private final Boolean initialized = Boolean.FALSE;
synchronized(initialized) { 
  if (!initialized) {
    // Perform initialization
    initialized = Boolean.TRUE;
  }
}

There can be two possible valid values (true and false of the variable initialized, discounting null) that a Boolean can assume. Consequently, any other code that synchronizes on a Boolean variable with the same value, may cause unresponsiveness and deadlocks [[Findbugs 08]].

Noncompliant Code Example (Boxed primitive)

This noncompliant code example locks on a boxed Integer object.

int lock = 0;
final Integer Lock = lock; // Boxed primitive Lock will be shared
synchronized(Lock) { /* ... */ }

Boxed types are allowed to use the same instance for a range of integer values and consequently, suffer from the same problems as Boolean 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 (String constant)

This noncompliant code example locks on a final String literal.

// This bug was found in jetty-6.1.3 BoundedThreadPool
private final String _lock = "LOCK";
synchronized(_lock) { /* ... */ }

A String literal is a constant and is interned. 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 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.

Consequently, a String constant behaves like a global variable in the JVM. As demonstrated in this noncompliant code example, even if every instance of an object maintains its own field lock, the field points to a common String constant in the JVM. Trusted code that locks on the same String constant renders all synchronization attempts inadequate. Likewise, hostile code from any other package can exploit this vulnerability.

Compliant Solution (private internal raw Object)

This compliant solution uses an internal private lock object. This is one of the few cases where a raw Object is useful.

private final Object lock = new Object();

synchronized(lock) { 
  // ...
}

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).

synchronized(getClass()) { /* ... */ }

Section 4.3.2 "The Class Object" of the Java Language specification [[JLS 05]] describes how method synchronization works:

A class method that is declared synchronized synchronizes on the lock associated with the Class 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 want 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 example) in the synchronization block.

synchronized(SuperclassName.class) { 
  // ... 
}

The class object being synchronized must 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 lock object.

Compliant Solution (Class.forName())

This compliant solution uses the Class.forName() method to synchronize on the superclass's Class object.

synchronized(Class.forName("SuperclassName")) { 
  // ... 
}

Again, the class object being synchronized must not be accessible to hostile code, as discussed in the previous example.

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) { /* ... */ }

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.

final Lock lock = new ReentrantLock();
lock.lock();
try {
  // ...
} finally {
  lock.unlock();
}

Noncompliant Code Example (collection view)

This noncompliant code example synchronizes on the view of a synchronized map.

private final Map<Integer, String> map = Collections.synchronizedMap(new HashMap<Integer, String>());
private final Set<Integer> set = map.keySet();
synchronized(set) {  // Incorrectly synchronizes on set
  for(Integer k : set) { 
    // Do something 
  }
}

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]].

The Collections class documentation [[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.

// ...
Map<Integer, String> map = Collections.synchronizedMap(new HashMap<Integer, String>());
synchronized(map) {  // Synchronize on map, not set
  for(Integer k : map) { 
    // Do something  
  }
}

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.

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, Collections
[[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

  • No labels