Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added NCE/CS and nicknames

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

This noncompliant code example locks on a non-final nonfinal 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 (final lock object)

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 (String constant)

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

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

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

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

...

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

Compliant Solution (class name qualification)

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 (collection view)

Wiki Markup
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|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 (collection lock object)

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

This noncompliant code example uses a nonstatic lock object to guard access to a static field. If two threads 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 length because the increment operation on volatile fields is not atomic, in the absence of proper synchronization.

Code Block
bgColor#FFcccc

class PackBox implements Runnable {
  static volatile int length;
  // ...

  Object lock = new Object();    

  public void run() {
    synchronized(lock) {
      length++; // Dimensions after packing the box	 
      // ... 
    } 
  }

  public static void main(String[] args) {
    Runnable r1 = new Box();
    Thread t1 = new Thread(r1);
    Runnable r2 = new Box();
    Thread t2 = new Thread(r2);
    t1.start();
    t2.start();
  }
}

Compliant Solution (static lock object)

This compliant solution declares the lock object as static to ensure that the increment operation is carried out atomically using a shared lock object.

Code Block
bgColor#ccccff

class PackBox implements Runnable {
  static volatile int length;
  // ...

  static Object lock = new Object();    
  // ...
}

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

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.

...