...
The Java programming language allows threads to access shared variables. If, in In this noncompliant code example, if one thread repeatedly calls the method one()
, and another thread repeatedly calls the method two()
:, then method two()
could occasionally print a value of i
that is neither zero nor the value of the argument j
.
Code Block | ||
---|---|---|
| ||
class Test { static long i = 0; static void one(long j) { i = j; } static void two() { System.out.println("i =" + i); } } |
then method two()
could occasionally print a value for i
that is neither zero nor a previous value of j
. A similar problem occurs may occur if i
is declared as a double
.
...
Code Block | ||
---|---|---|
| ||
class Test { static volatile long i = 0; static void one(final long j) { i = j; } static void two() { System.out.println("i =" + i); } } |
It is important to ensure that the argument to method one()
is obtained from a volatile
variable or as a result of passing an explicit integer value. Otherwise, the variable read may itself be susceptible to the described vulnerability.
Semantics of volatile
do not Volatile semantics does guarantee the atomicity of complex operations that involve read-modify-write sequences such as incrementing a value. See VOID CON00CON01-J. Synchronize access to shared mutable variablesEnsure visibility of shared variables and atomicity of composite operations for more information.
Exceptions
CON25-EX1: If all reads and writes of 64 bit long
and double
values occur within a synchronized method callscall, 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. (CON01-J. Ensure visibility of shared variables and atomicity of composite operations)
CON25-EX2: Systems that guarantee that 64 bit long
and double
values are read and written as atomic operations may safely ignore this guideline.
...
Failure to ensure the atomicity of operations involving 64-bit values in multithreaded multi-threaded applications can result in reading and writing indeterminate values.
...