...
- 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 VNA02-J. Ensure that compound operations on shared variables are atomic.")
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 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 VNA05-J. Ensure atomicity when reading and writing 64-bit values.")
Noncompliant Code Example (Non-Volatile Flag)
...