Does mutation of an non-thread-safe collection in a constructor need to be synchronized?

后端 未结 4 1458
庸人自扰
庸人自扰 2021-02-19 02:20

If I decide to use a non-thread-safe collection and synchronize its access, do I need to synchronize any mutation in the constructor? For example in the following code, I under

4条回答
  •  我在风中等你
    2021-02-19 03:22

    According to the JLS

    The usage model for final fields is a simple one: Set the final fields for an object in that object's constructor; and do not write a reference to the object being constructed in a place where another thread can see it before the object's constructor is finished.

    Since the write to the List occurs prior to the constructor completing you are safe in mutating the list without additional synchronization.

    edit: Based on Voo's comment I will make edit with the inclusion of final field freezing.

    So reading more into 17.5.1 there is this entry

    Given a write w, a freeze f, an action a (that is not a read of a final field), a read r1 of the final field frozen by f, and a read r2 such that hb(w, f), hb(f, a), mc(a, r1), and dereferences(r1, r2),

    I interpret this as the action to modify the array happens-before the later derefencing of r2 which is the non-synchronized read after the freeze completes (the constructor exists).

提交回复
热议问题