2.1 VNA00-J. Ensure visibility when accessing shared primitive variables
Reading a shared primitive variable in one thread may not yield the value of the most recent write to the variable from another thread. Consequently, the thread may observe a stale value of the shared variable. To ensure the visibility of the most recent update, either the variable must be declared volatile or the reads and writes must be synchronized.
Declaring a shared variable volatile guarantees visibility in a thread-safe manner only when both of the following conditions are met: â¢
- A write to a variable does not depend on its current value.
...
- A write to a variable does not depend on the result of any non-atomic compound operations involving reads and writes of other variables. (For more information, see guideline âVNA02-J. Ensure that compound operations on shared variables are atomic.")
The first condition can be relaxed when you can be sure that only one thread will ever update the value of the variable Goetz 2006. However, code that relies on a single-thread confinement is error-prone and difficult to maintain. This behavior is permissible under this guideline but not recommended.
Synchronizing the code makes it easier to reason about its behavior and is frequently more secure than simply using the volatile keyword. However, synchronization has a somewhat higher performance overhead and can result in thread contention and deadlocks when used excessively.
Declaring a variable volatile or correctly synchronizing the code guarantees that 64-bit primitive long and double variables are accessed atomically. (For more information on sharing those variables among multiple threads, see guideline âVNA05-J. Ensure atomicity when reading and writing 64-bit values.")
...
Noncompliant Code Example (Non-Volatile Flag)
This noncompliant code example uses a shutdown() method to set a non-volatile done flag that is checked in the run() method.
...