Versions Compared

Key

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

...

This behavior can be result in reading indeterminate values in code that is required to be thread-safe.

Noncompliant Code Example

The Java programming language allows threads to access shared variables. If, in this noncompliant code example, one thread repeatedly calls the method one() (but no more than Integer.MAX_VALUE times in all), and another thread repeatedly calls the method two():

...

then method two() could occasionally print a value for i that is not one more than the previous value printed by two(). A similar problem occurs if i is declared as a double.

Compliant Solution

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

Code Block
bgColor#ccccff
class Test {
  static long i = 0;
  static void one() { i++; }
  static void two() {
    System.out.println("i =" + i);
  }
}

Compliant Solution

This compliant solution synchronizes calls to methods one() and two(). This guarantees these two method calls are treated as atomic operation, including reading and writing to the variable i.

...

Consequently, there is no need to qualify i as a volatile type.

Risk Assessment

Failure to ensure the atomicity of operations involving 64-bit values in multithreaded applications can result in reading and writing indeterminate values.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CON39- J

low

probable

medium

P4

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[JLS 05|AA. Java References#JLS 05]\] 17.7 Non-atomic Treatment of double and long
\[[Goetz 06|AA. Java References#Goetz 06]\] 3.1.2. Nonatomic 64-bit Operations

...