Versions Compared

Key

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

...

Consider, for example, a scenario where the standard thread-safe API does not provide a single method to both find a particular person's record in a Hashtable and also update the corresponding payroll information. In such cases, a custom atomic the two method invocations must be designed and usedperformed atomically.

Enumerations and iterators also require explicit synchronization on the collection object (client-side locking) or a private final lock object.

Compound operations on shared variables are also non-atomic. See CON01-J. Ensure that compound operations on shared variables are atomic for more information.

CON30-J. Do not use method chaining implementations in a multi-threaded environment describes a specialized case of this guideline.

Noncompliant Code Example (AtomicReference)

...

An AtomicReference is an object reference that can be updated atomically. Operations that use two atomic references independently, are guaranteed to be atomic, however, if an operation involves using both together, the resulting combined operation is not atomic. However, operations combining more than one atomic reference are not atomic. In this noncompliant code example, one thread may call update() while a second thread may call add(). This might cause the add() method to add the new value of first to the old value of second, yielding an erroneous result.

...

Code Block
bgColor#ccccff
final class Adder {
  // ...

  public synchronized void update(BigInteger f, BigInteger s){
    first.set(f);
    second.set(s);
  }

  public synchronized BigInteger add() {
    return first.get().add(second.get()); 
  }
}

Prefer using block synchronization instead of method synchronization when the method contains non-atomic operations that either do not require any synchronization or can use a more fine-grained locking scheme involving multiple private final lock objects. Non-atomic operations can be decoupled from those that require synchronization and executed outside the synchronized block. The guideline CON04-J. Use private final lock objects to synchronize classes that may interact with untrusted code has more details on using private final lock objects and block synchronization.

Noncompliant Code Example (synchronizedList)

This noncompliant code example uses a java.util.ArrayList<E> collection, which is not thread-safe by default. However, the Collections.synchronizedList is used as a synchronization wrapper for ArrayList.

...