Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki MarkupCode 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|AA. Java References#Pugh 08]\]

There are several common errors with synchronizing on objects:

...

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 locks synchronizes on a public nonfinal Boolean lock object.

Code Block
bgColor#FFcccc

public Object publicLockprivate final Boolean initialized = new Object()Boolean.FALSE;

privatepublic void doSomething() {
  synchronized (publicLockinitialized) { 
    // body...
  }
}

It The Boolean type is possible for untrusted code to change the value of the lock object and foil all attempts to synchronizeunsuitable 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 synchronizes locks on a nonfinal field and demonstrates no mutual exclusion propertiesboxed Integer object.

Code Block
bgColor#FFcccc
private int count = 0;
private final Integer lockLock = new Integer(0);

private count; // Boxed primitive Lock is shared

public void doSomething() {
  synchronized (lockLock) {
 /* ... */ }
}

public void setLock(Integer lockvalue) {
  lock = lockValue;
}

This is because the thread that holds a lock on the nonfinal field object can modify the field's value to reference some other object. This might cause two threads that lock on the same field to actually not lock on the same object, causing them to execute critical sections of code simultaneously.

Compliant Solution (private and final lock object)

 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, LockThis compliant solution synchronizes using a lock object that is declared as final.

Code Block
bgColor#ccccff
private int count = 0;
private final Integer lockLock = new Integer(0count);

privatepublic void doSomething() {
  synchronized(lock) { /* ... */ }
}

// setValue() is disallowed

Noncompliant Code Example (Boolean lock object)

Wiki Markup
This noncompliant code example uses a {{Boolean}} field to synchronize. However, since the field is not {{final}}, there can be two possible valid values ({{true}} and {{false}}, discounting {{null}}) that a {{Boolean}} can assume. Consequently, any other code that synchronizes on the same value can cause unresponsiveness and deadlocks \[[Findbugs 08|AA. Java References#Findbugs 08]\].

Code Block
bgColor#FFcccc

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

Noncompliant Code Example (Boxed primitive)

This noncompliant code example locks on a non-final boxed Integer object.

Code Block
bgColor#FFcccc

int lock = 0;
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 insecureWhen 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 a final an interned String literal object.

Code Block
bgColor#FFcccc

// This bug was found in jetty-6.1.3 BoundedThreadPool
private final String lock = new String("oneLOCK").intern();

public void doSomething() {
  synchronized (lock) {
    /*/ ...
 */ }
}

...

A {{String}} literal is a constant and is interned. According to the Java API \[[API 06|AA. Java References#API 06]\], class {{String}} documentationAPI class java.lang.String documentation [API 2006]:

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 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, 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. Likewise. 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.

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
bgColor#FFcccc

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 the Class object of the class.

This does not mean that a subclass locking 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.

Compliant Solution (class name qualification)

Explicitly define the name of the class through name qualification (superclass in this example) in the synchronization block.

Code Block
bgColor#ccccff

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

The class object being synchronized must not be accessible to hostile code. For more information, see CON04-J. Use the private lock object idiom instead of the Class object's intrinsic locking mechanism.

Compliant Solution (2) (Class.forName())

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

Code Block
bgColor#ccccff

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

The class object being synchronized must not be accessible to hostile code. For more information, see CON04-J. Use the private lock object idiom instead of the Class object's intrinsic locking mechanism, 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.

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.

Wiki MarkupWhen 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]\].

Code Block
bgColor#FFcccc

Map<Integer, String> m = Collections.synchronizedMap(new HashMap<Integer, String>());
Set<Integer> s = m.keySet();
synchronized(s) {  // IncorrectlyThis synchronizesbug onwas s
found  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.

Code Block
bgColor#ccccff

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

Noncompliant Code Example (ReentrantLock lock object)

This noncompliant code example incorrectly uses a ReentrantLock as the lock object.

Code Block
bgColor#FFcccc

final Lock lock = new ReentrantLock();
synchronized(lock) { /* ... */ }

This problem usually comes up in practice when refactoring from intrinsic locking to the java.util.concurrent 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.

Code Block
bgColor#ccccff

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

Noncompliant Code Example (nonstatic lock object for static data)

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 counter because the increment operation on volatile fields is not atomic in the absence of proper synchronization.

in jetty-6.1.3 BoundedThreadPool
private final String lock = "LOCK";

public void doSomething() {
  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 instance.

Code Block
bgColor#ccccff
private final String lock = new String("LOCK");

public void doSomething
Code Block
bgColor#FFcccc

class CountBoxes implements Runnable {
  static volatile int counter;
  // ...

  Object lock = new Object();    

  public void run() {
  synchronized  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();
  }
}

Noncompliant Code Example (method synchronization for static data)

This noncompliant code example uses method synchronization to protect access to a static class member.

Code Block
bgColor#FFcccc

class CountBoxes implements Runnable {
  static volatile int counter;
  // ...

  public synchronized void run() {
      counter++; 
      // ... 
  }
  // ...
}

The problem is that this lock is associated with each instance of the class and not with the class object itself. Consequently, threads constructed using different Runnable instances may observe inconsistent values of the counter.

Compliant Solution (static lock object)

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 usefulThis compliant solution declares the lock object as static and consequently, ensures the atomicity of the increment operation.

Code Block
bgColor#ccccff

class CountBoxes implements Runnable {
  static int counter;
  // ...

  private static final Object lock = new Object();    
  
  public void rundoSomething() {
  synchronized  synchronized(lock) {
      counter++; 
      // ...
  }
  // ...
}

There is no requirement of declaring the counter variable as volatile when synchronization is usedFor 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

Synchronizing on an incorrect variable can provide a false sense of thread safety and result in nondeterministic behaviorA 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 synchronize.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

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

ToolVersionCheckerDescription
The Checker Framework

Include Page
The Checker Framework_V
The Checker Framework_V

Lock CheckerConcurrency and lock errors (see Chapter 6)
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V
FB.MT_CORRECTNESS.DL_SYNCHRONIZATION_ON_BOOLEAN
FB.MT_CORRECTNESS.DL_SYNCHRONIZATION_ON_BOXED_PRIMITIVE
FB.MT_CORRECTNESS.DL_SYNCHRONIZATION_ON_SHARED_CONSTANT
Synchronization on Boolean
Synchronization on boxed primitive
Synchronization on interned String
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
TRS.SCSImplemented
SonarQube
Include Page
SonarQube_V
SonarQube_V
S1860 
ThreadSafe
Include Page
ThreadSafe_V
ThreadSafe_V

CCE_CC_REUSEDOBJ_SYNC

Implemented

Bibliography

[API 2006]

Class String, Collections

[Findbugs 2008]

 

[Miller 2009]

Locking

[Pugh 2008]

Synchronization

[Tutorials 2008]

Wrapper Implementations

 

...

Image Added Image Added Image AddedVOID CON00-J. Synchronize access to shared mutable variables      11. Concurrency (CON)      CON03-J. Do not use background threads during class initialization