Reads of shared primitive variables in some thread may not observe the latest writes to them the variables from other threads. It is important to ensure that the accesses see the value values of the latest most recent 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 by declaring variables volatile
or correctly synchronizing the code.
...
- A write to a variable does not depend on its current value
- The write is not involved with writes of other variables
Both approaches also Furthermore, declaring a variable as volatile or correctly synchronizing the code guarantee that 64-bit primitive variables of type long
and double
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).
...
This compliant solution uses the intrinsic lock of the Class
object to ensure thread safetythat updates are visible to other threads.
Code Block | ||
---|---|---|
| ||
final class ControlledStop implements Runnable { private boolean done = false; public void run() { while (!isDone()) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { // handle exception } } } protected synchronized boolean isDone() { return done; } protected synchronized void shutdown() { done = true; } } |
While this is an acceptable compliant solution, it has the following disadvantages shortcomings as compared to declaring done
as volatile
:
- Performance: The intrinsic locks cause threads to block temporarily;
volatile
incurs no blocking - Deadlock: Improper use of locks can lead to deadlocks. Because the use of
volatile
incurs no blocking, deadlock cannot occurExcessive synchronization can make the program deadlock prone.
However, synchronization is a useful more secure alternative in situations where the volatile
keyword is inappropriate, such as if a variable's new value depends on its old value. Refer to CON01-J. Do not assume that composite operations are atomic and CON07-J. Do not assume that a grouping of calls to independently atomic methods is atomic for more details.
...
Failing to ensure visibility of atomically modifiable shared primitive variables on accesses can lead to a thread seeing stale values of a the variable.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON00- J | medium | probable | medium | P8 | L2 |
...