The volatile key word and memory consistency errors

前端 未结 4 732
谎友^
谎友^ 2021-02-09 11:28

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

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

4条回答
  •  鱼传尺愫
    2021-02-09 11:59

    Ad 1: With a volatile variable, the variable is always checked against a master copy and all threads see a consistent state. But if you use that volatility variable in a non-atomic operation writing back the result (say a = f(a)) then you might still create a memory inconsistency. That's how I would understand the remark "reduces the risk". A volatile variable is consistent at the time of read, but you still might need to use a synchronize.

    Ad 2: I don't know. But: If your definition of "happens before" includes the remark

    This means that changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.

    I would not dare to rely on any other property except that volatile ensures this. What else do you expect from it?!

提交回复
热议问题