是否需要同步构造函数中非线程安全集合的突变?
如果我决定使用非线程安全集合并同步其访问,是否需要同步构造函数中的任何突变?例如,在下面的代码中,我理解对列表的引用将在构造后对所有线程可见,因为它是最终的。但我不知道这是否构成安全发布,因为构造函数中的 add 不是同步的,并且它正在 ArrayList 的 elementData 数组中添加一个引用,这是非最终的。
private final List<Object> list;
public ListInConstructor()
{
list = new ArrayList<>();
// synchronize here?
list.add(new Object());
}
public void mutate()
{
synchronized (list)
{
if (list.checkSomething())
{
list.mutateSomething();
}
}
}