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 as volatile or the reads and writes must be synchronized correctly to the variable.
Declaring a shared variable as 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.")
...
unmigrated-wiki-markup
The first condition can be relaxed when you can be sure that only one thread will ever update the value of the variable \[[Goetz 06|AA. Java References#Goetz 06]\]. However, code that relies on an invariant such as single-thread confinement to be true at all times is error-prone and difficult to maintain. This behavior is permissible under this guideline but not 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 as volatile or correctly synchronizing the code guarantees that 64-bit primitive long and double variables are accessed atomically. (For more information on sharing long
and double
those variables among multiple threads, see VNA05guideline âVNA05-J. Ensure atomicity when reading and writing 64-bit values.")
Noncompliant Code Example (Non-volatile Flag)
...