Volatile guarantee safe publication of a mutable object?

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

    We need to show that constructing an object and assigning it to a volatile variable happens before it is read from that variable.

    From JLS Chapter 17:

    If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).

    So, construction of an object happens before it is assigned to a volatile variable, from the point of view of that thread.

    If an action x synchronizes-with a following action y, then we also have hb(x, y).

    And:

    If hb(x, y) and hb(y, z), then hb(x, z).

    If we could show that writing the volatile variable (action y) synchronizes-with reading the variable (action z), we could use the transitivity of happens-before to show that constructing the object (action x) happens-before reading the object. Luckily:

    A write to a volatile variable v (§8.3.1.4) synchronizes-with all subsequent reads of v by any thread (where "subsequent" is defined according to the synchronization order).

    Therefore, we can see that a properly constructed object is visible to any thread when published this way.

提交回复
热议问题