Reading a shared primitive variable in one thread may not yield the value of the latest write to the variable from another thread. It is important to ensure that a read of a shared variable sees the value of the most recent write to the variable. If this is not done, multiple threads may observe stale values of the shared variable and fail to act accordingly. Visibility of the latest value can be ensured by declaring the variable volatile
or correctly synchronizing the reads and writes to the variable.
Wiki Markup |
---|
The use of {{volatile}} is recommended under a very restrictive set of conditions \[[Goetz 06|AA. Java References#Goetz 06]\]: |
- A write to a variable does not depend on its current value.
- The write is not involved with writes of other variables.
- Only a single thread ever updates the value.
- Locking is not required for any other reason.
Synchronizing the code makes it easier to reason about the behavior of the code and is frequently a more secure approach than using volatile
, however, it is slightly more expensive. Excessive use of synchronization can also lead to deadlocks.
Declaring Furthermore, declaring a variable as volatile or correctly synchronizing the code guarantees that 64-bit primitive variables of type long
and double
are 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).
...