Versions Compared

Key

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

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

Noncompliant Code Example

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 any attempts to synchronize.

Code Block
bgColor#FFcccc
public Object publicLock = new Object();
synchronized(publicLock) { 
  // body
}

Compliant Solution

This compliant solution synchronizes on a private final object and is safe from malicious manipulation.

Code Block
bgColor#ccccff
private final Object privateLock = new Object();
synchronized(privateLock) { 
  // body
}

Noncompliant Code Example

Wiki Markup
A {{String}} constant is interned in Java. According to the Java API \[[API 06|AA. Java References#API 06]\] Class {{String}} documentation:

...

Code Block
bgColor#FFcccc
// 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 demonstrates no mutual exclusion properties. This is because the thread that holds a lock on the field can modify the referenced object's value which 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.

...

In general, holding a lock on any data structure that contains a boxed value can be dangerous.

Noncompliant Code Example

Wiki Markup
This noncompliant code example uses a {{Boolean}} field to synchronize. However, there can only be two possible 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|AA. Java References#Findbugs 08]\].

Code Block
bgColor#FFcccc
private Boolean initialized = Boolean.FALSE;
synchronized(initialized) { 
  if (!initialized) {
    // Perform initialization
    initialized = Boolean.TRUE;
  }
}

Compliant Solution

In the absence of an existing object to lock on, using a raw object to synchronize suffices.

...

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

Noncompliant Code Example

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.

...

This does not mean that it is required to synchronize on the Class object of the base class.

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.

...

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 ([CON06-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
bgColor#FFcccc
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
bgColor#ccccff
// ...
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
bgColor#FFcccc
final Lock lock = new ReentrantLock();
synchronized(lock) { /* ... */ }

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

CON01 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

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]

...