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. Visibility To ensure the visibility of the most recent update can be ensured by declaring , declare the variable as volatile or correctly synchronizing synchronize the reads and writes to the variable.
...
- 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. (see See CON01-J. Ensure that compound operations on shared variables are atomic for more information.)
Wiki Markup |
---|
The first condition can be 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, 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 recommended. |
...