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

后端 未结 4 1457
庸人自扰
庸人自扰 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:23

    Update: The Java Language Specification states that the freeze making the changes visible must be at the end of the constructor, which means your code is correctly synchronized, see the answers from John Vint and Voo.

    However you can also do this, which definitely works:

    public ListInConstructor()
    {
        List tmp = new ArrayList<>();
        tmp.add(new Object());
        this.list = tmp;
    }
    
    
    

    Here we mutate the list object before assigning it to the final field, and so the assignment will guarantee that any changes made to the list will also be visible.

    17.5. final Field Semantics

    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. If this is followed, then when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields. It will also see versions of any object or array referenced by those final fields that are at least as up-to-date as the final fields are.

    The highlighted sentence gives you a guarantee that this solution will work. Although, as pointed out at the start of the answer, the original has to work too, but I'll leave this answer here as the specification is slightly confusing. And because this "trick" also works when setting non-final but volatile fields (from any context, not just constructors).

    提交回复
    热议问题