Volatile guarantee safe publication of a mutable object?

后端 未结 3 1953
星月不相逢
星月不相逢 2021-02-14 18:56

By reading Java Concurrency in Practice

I can see:

To publish an object safely, both the reference to the object and the object\'s state must be

3条回答
  •  天涯浪人
    2021-02-14 19:46

    Reads and writes are atomic for all variables declared volatile (including long and double variables).

    Consequence: volatile guarantees, among others, that the variable is always read from the memory shared by all threads - if the value is published in a volatile variable, it must be fully constructed before.
    In other words, if a volatile value is not published, then no other threads will know about it - most probably the result of 'construction in progress' may reside in the CPU cache or in the memory that JVM uses as "space I'm using for my own purposes; you puny Java code, don't ask what's in it, it's not your business".

提交回复
热议问题