What does “subsequent read” mean in the context of volatile variables?

后端 未结 5 734
北恋
北恋 2020-12-14 21:33

Java memory visibility documentation says that:

A write to a volatile field happens-before every subsequent read of that same field.

5条回答
  •  佛祖请我去吃肉
    2020-12-14 21:55

    This is more a definition of what will not happen rather than what will happen.

    Essentially it is saying that once a write to an atomic variable has happened there cannot be any other thread that, on reading the variable, will read a stale value.

    Consider the following situation.

    • Thread A is continuously incrementing an atomic value a.

    • Thread B occasionally reads A.a and exposes that value as a non-atomic b variable.

    • Thread C occasionally reads both A.a and B.b.

    Given that a is atomic it is possible to reason that from the point of view of C, b may occasionally be less than a but will never be greater than a.

    If a was not atomic no such guarantee could be given. Under certain caching situations it would be quite possible for C to see b progress beyond a at any time.

    This is a simplistic demonstration of how the Java memory model allows you to reason about what can and cannot happen in a multi-threaded environment. In real life the potential race conditions between reading and writing to data structures can be much more complex but the reasoning process is the same.

提交回复
热议问题