...
This behavior can result in indeterminate values being read in code that is required to be thread-safe.
Noncompliant Code Example
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.
...
A similar problem may occur if i
is declared as a double
.
Compliant Solution (Volatile)
This compliant solution declares i
as volatile. Writes and reads of long
and double
volatile values are always atomic.
...
Semantics of volatile
do not guarantee the atomicity of compound operations that involve read-modify-write sequences such as incrementing a value. See CON02-J. Ensure that compound operations on shared variables are atomic for more information.
Exceptions
CON25CON05-EX1: If all reads and writes of 64-bit long
and double
values occur within a synchronized region, the atomicity of the read/write is guaranteed. This requires that no unsynchronized methods in the class expose the value and that the value is inaccessible (directly or indirectly) from other code. (For more information, see CON02-J. Ensure that compound operations on shared variables are atomic.)
CON25CON05-EX2: Systems that guarantee that 64-bit long
and double
values are read and written as atomic operations may safely ignore this guideline.
Risk Assessment
Failure to ensure the atomicity of operations involving 64-bit values in multithreaded applications can result in reading and writing indeterminate values. Many Java Virtual Machines (JVMs) read and write 64-bit values atomically, even though the specification does not require them to.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON25 CON05- J | low | unlikely | medium | P2 | L3 |
Related Vulnerabilities
Any vulnerabilities resulting from the violation of this rule are listed 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. Non-Atomic 64-Bit Operations \[[Goetz 04c|AA. Java References#Goetz 04c]\] \[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 667|http://cwe.mitre.org/data/definitions/667.html] "Insufficient Locking" |
Issue Tracking
Tasklist | ||||
---|---|---|---|---|
| ||||
||Completed||Priority||Locked||CreatedDate||CompletedDate||Assignee||Name|| |F|M|F|1269650712386| |dmohindr|Section 17.7 "Non-Atomic Treatment of {{double}} and {{long}}" ... Non-Atomic is Non-atomic in JLS 05, should we retain the lower-case for "atomic" as given in the reference?| |
...