Volatile guarantee safe publication of a mutable object?

后端 未结 3 1955
星月不相逢
星月不相逢 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:29

    volatile can only guarantee that the reference is visible to another thread but it doesn't have synchronization of object construction which it refers to.

    Yes. You are right. You can find more details of internals about volatile variables in below question:

    Difference between volatile and synchronized in Java

    So how can it guarantee that the mutable object is properly constructed, what is the thread that is constructing this object is interrupted by another thread?

    You have to use other programming constructs for thread safety : Using synchronized constructs or alternatives of synchronized constructs.

    Refer to below related SE question:

    Avoid synchronized(this) in Java?

提交回复
热议问题