Does a volatile reference really guarantee that the inner state of the object is visible to other threads?

微笑、不失礼 提交于 2019-12-12 03:48:58

问题


While reading "Java Concurrency in Practice", I came across the following -

To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by:

  • Initializing an object reference from a static initializer;
  • Storing a reference to it into a volatile field or AtomicReference;
  • Storing a reference to it into a final field of a properly constructed object; or
  • Storing a reference to it into a field that is properly guarded by a lock.

My question is - is the second point true? I.e. Can I make an Object's state visible to other threads just by storing a reference to it in a volatile reference? If not, am I reading the above points incorrectly?


回答1:


Making object volatile doesn't make his state published to all the Threads, ie

volatile A a = new A();
private static class A {
    int i = 0;
    int j = 0;
    int k = 0;
}

is not the same as

A a = new A();
private static class A {
    volatile int i = 0;
    volatile int j = 0;
    volatile int k = 0;
}

(1) rather makes your reference volatile, ie if one Thread reassigns the reference, this reassignment will be "published" to other Threads immediately



来源:https://stackoverflow.com/questions/36200870/does-a-volatile-reference-really-guarantee-that-the-inner-state-of-the-object-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!