Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added bit-logic NCCE/CS set

...

The Java Language Specification also permits reads and writes of 64-bit values to be non-atomic though this is not an issue with most modern JVMs (see CON25-J. Ensure atomicity when reading and writing 64-bit values).

Noncompliant Code Example (bitwise logic)

This class maintains a set of flags, which can be set and cleared independently. They are stored in a single byte field.

Code Block
bgColor#FFcccc

class Flags {
  public static final byte FLAG_1 = 1
  public static final byte FLAG_2 = 2;
  public static final byte FLAG_4 = 4;
  public static final byte FLAG_8 = 8;

  private byte flags = 0;

  public void setFlag(byte flag) {
    flags |= flag;
  }

  public void clearFlag(byte flag) {
    flags &= ~flag;
  }
} 

This class is not thread-safe at all, even though only one value is modified. For instance, suppose Thread 1 calls setFlag( FLAG_1) while Thread 2 calls setFlag( FLAG_2). The following represents one possible execution of the two threads:

Time

flags=

Thread

Action

1

0

t1

reads the current value of flags, 0, into a temporary variable

2

0

t2

reads the current value of flags, (still) 0, into a temporary variable

3

0

t1

sets the 1st byte, creating the value 1

4

0

t2

sets the 2nd byte, creating the value 2

5

1

t1

writes the temporary variable value to flags

6

2

t2

writes the temporary variable value to flags

As a result, the effect of the call by t1 is not reflected in flags; the program behaves as if the call was never made.

Furthermore, it is quite likely that if one thread sets a flag, and another thread retrieves the flags value, the second thread will not see the setting from the first thread.

Noncompliant Code Example (volatile)

In this noncompliant code example, the {[flags}} field is volatile.

Code Block
bgColor#FFcccc

class Flags {
  public static final byte FLAG_1 = 1
  public static final byte FLAG_2 = 2;
  public static final byte FLAG_4 = 4;
  public static final byte FLAG_8 = 8;

  private volatile byte flags = 0;

  public void setFlag(byte flag) {
    flags |= flag;
  }

  public void clearFlag(byte flag) {
    flags &= ~flag;
  }
} 

The volatile keyword guarantees that any writes to the flags variable will be seen by any subsequent reads. However, the volatile keyword does not prevent the exedcution scenario described above. In particular, it does not guarantee that the read of the flags variable followed by the write of the flags variable is atomic.

Compliant Solution (java.util.concurrent.atomic classes)

The java.util.concurrent utilities can be used to atomically manipulate a shared variable. In this compliant solution, flags is an AtomicInteger, allowing composite operations to be performed atomically.

Code Block
bgColor#ccccff

class Flags {
  private AtomicInteger flags = new AtomicInteger( 0);

  public void setFlag(byte flag) {
    while (true) {
      int old = flags.get();
      int next = old | flag;
      if (flags.compareAndSet( old, next)) {
        break;
      }
    }
  }

  public void clearFlag(byte flag) {
    while (true) {
      int old = flags.get();
      int next = old & ~flag;
      if (flags.compareAndSet( old, next)) {
        break;
      }
    }
  }
} 

Note that updates to shared atomic variables are visible to other threads.

Wiki Markup
The {{compareAndSet()}} method takes two arguments, the expected value of a variable when the method is invoked and the updated value. This compliant solution uses this method to atomically set the value of {{flags}} to the updated value if and only if the current value equals the expected value \[[API 06|AA. Java References#API 06]\].  The {{while}} loop ensures that each  method persists in trying to set {{flags}} until it succeeds.

Compliant Solution (synchronization)

This compliant solution uses synchronization to protect access to the flags field. Synchronization provides a way to safely share object state across multiple threads without the need to reason about reorderings, compiler optimizations, and hardware specific behavior.

Code Block
bgColor#ccccff

class Flags {
  private byte flags = 0;
  private Object lock = new Object();

  public void setFlag(byte flag) {
    synchronized (lock) {
      flags |= flag;
    }
  }

  public void clearFlag(byte flag) {
    synchronized (lock) {
      flags &= ~flag;
    }
  }
} 

If code is synchronized correctly, updates to shared variables are instantly made visible to other threads. Synchronization is more expensive than using the optimized java.util.concurrent utilities and should generally be preferred when it is sufficiently complex to carry out the operation atomically using the utilities. When using synchronization, care must be taken to avoid deadlocks (see CON12-J. Avoid deadlock by requesting and releasing locks in the same order).

Constructors and methods can use block synchronization as an alternative to method synchronization. Block synchronization synchronizes a block of code rather than a method, as shown in this compliant solution. Block synchronization can also synchronize on a lock besides the object's intrinsic lock, as is recommended by CON04-J. Use the private lock object idiom instead of the Class object's intrinsic locking mechanism.

Noncompliant Code Example (increment/decrement)

Prefix and postfix, increment and decrement operations are non-atomic in that the value written depends upon the value initially read from the operand. For example, x++ is non-atomic because it is a composite operation consisting of three discrete operations: reading the current value of x, adding one to it, and writing the new, incremented value back to x.

...

As a result, both threads decrement itemsInInventory but the range check on the variable is bypassed, causing the variable to have an invalid value. The decrement operation may even wrap if MIN_INVENTORY == Integer.MIN_VALUE.

Noncompliant Code Example (volatile)

This noncompliant code example attempts to resolve the problem by declaring itemsInInventory volatile.

...

Volatile variables are unsuitable when more than one read/write operation needs to be atomic. The use of a volatile variable in this noncompliant code example guarantees that once itemsInInventory has been updated, the new value is visible to all threads that read the field. However, because the post decrement operator is nonatomic, even when volatile is used, the interleaving described in the previous noncompliant code example is still possible. Furthermore, the race codnition imposed by range-checking itemsInInventory before decrementing it is also still possible.

Compliant Solution (java.util.concurrent.atomic classes)

The java.util.concurrent utilities can be used to atomically manipulate a shared variable. This compliant solution defines intemsInInventory as a java.util.concurrent.atomic.AtomicInteger variable, allowing composite operations to be performed atomically.

...