Reads of shared primitive variables in some thread may not observe the latest writes to them from other threads. It is important to ensure that the accesses see the value of the latest writes. If this is not done, multiple threads may observe stale values of the shared variables and fail to act accordingly. Visibility of latest values can be ensured using by declaring variables volatile
or synchronizationcorrectly synchronizing the code.
The use of volatile
is recommended under a very restrictive set of conditions:
- A write to a variable does not depend on its current value
- The write is not involved with writes of other variables
Accesses of primitive variables are atomic, except for the Both approaches also guarantee that 64-bit primitive variables of type long
and double
variables; will always be accessed atomically (see CON25-J. Ensure atomicity when reading and writing 64-bit values for information on sharing long
and double
variables among multiple threads).
Noncompliant Code Example
...