Is this a safe publication of object?

前端 未结 2 1030
日久生厌
日久生厌 2020-12-10 07:18

I have a class Item

class Item {
  public int count;
  public Item(int count) {
    this.count = count;
  }
}

Then, I will put a reference

2条回答
  •  佛祖请我去吃肉
    2020-12-10 08:01

    Yes, there is a visibility problem, as Holder.item is not final. So there is no guarantee that another thread will see its initialized value after the construction of Holder is finished.

    And as @Gray pointed out, the JVM is free to reorder instructions in the absence of memory barriers (which can be created by a lock (synchronization), a final or volatile qualifier). Depending on the context, you must use one of these here to ensure safe publication.

提交回复
热议问题