The volatile key word and memory consistency errors

前端 未结 6 2010
借酒劲吻你
借酒劲吻你 2021-02-09 11:20

In the oracle Java documentation located here, the following is said:

Atomic actions cannot be interleaved, so they can be used without f

6条回答
  •  遇见更好的自我
    2021-02-09 12:06

    For question 1, the risk is only reduced (and not eliminated) because volatile only applies to a single read/write operation and not more complex operations such as increment, decrement, etc.

    For question 2, the effect of volatile is to make changes immediately visible to other threads. As the quoted passage states "this does not eliminate all need to synchronize atomic actions, because memory consistency errors are still possible." Simply because reads are atomic does not mean that they are thread safe. So establishing a happens before relationship is almost a (necessary) side-effect of guaranteeing memory consistency across threads.

提交回复
热议问题