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.
The use of {{ Wiki Markup volatile
}} is recommended under a very restrictive set of conditions, all of which must be met \[[Goetz 06|AA. Java References#Goetz 06]\] is safe under a very restrictive set of conditions, all of which must hold:
- A write to a variable does not depend on its current value, or it can be ensured that only a single thread ever updates the value
- The write is not involved with reads or writes of other variables
- Locking is not required for any other reason (all actions are atomic)
Wiki Markup |
---|
The first condition is sometimes relaxed when it can be ensured that only one thread ever updates the value of the variable \[[Goetz 06|AA. Java References#Goetz 06]\]. However, it is still possible for reader threads to see stale values of the variable while the writing thread is in the process of modifying its value, before writing it back. |
Synchronizing the code makes it easier to reason about its behavior and is frequently, a more secure approach than using volatile
. However, it is slightly more expensive and can cause deadlocks when used excessively.
...