Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added ThreadSafe detection

...

In this noncompliant code example, if one thread repeatedly calls the assignValue() method and another thread repeatedly calls the printLong() method, the printLong() method could occasionally print a value of i that is neither zero nor the value of the j argument.

Code Block
bgColor#FFcccc

class LongContainer {
  private long i = 0;

  void assignValue(long j) {
    i = j;
  }

  void printLong() {
    System.out.println("i = " + i);
  }
}

...

This compliant solution declares i volatile. Writes and reads of long and double volatile values are always atomic.

Code Block
bgColor#ccccff

class LongContainer {
  private volatile long i = 0;

  void assignValue(long j) {
    i = j;
  }

  void printLong() {
    System.out.println("i = " + i);
  }
}

...

Some static analysis tools are capable of detecting violations of this rule.

 ToolVersion Description 
ThreadSafe
Include Page
ThreadSafe_V
ThreadSafe_V
Implemented

Related Guidelines

MITRE CWE

CWE-667. Improper Locking

...

[Goetz 2006]

3.1.2, Non-atomic 64-Bit Operations

[Goetz 2004c]

 

[JLS 2005]

§17.7, Non-atomic Treatment of double and long

 

      07. Visibility and Atomicity (VNA)      08. Locking (LCK)