Is this a safe publication of object?

前端 未结 2 1017
日久生厌
日久生厌 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 07:53

    Can this new Item object be safely published? If not, why?

    The issue revolves around optimizations and reordering of instructions. When you have two threads that are using a constructed object without synchronization, it may happen that the compiler decides to reorder instructions for efficiency sake and allocate the memory space for an object and store its reference in the item field before it finishes with the constructor and the field initialization. Or it can reorder the memory synchronization so that other threads perceive it that way.

    If you mark the item field as final then the constructor is guaranteed to finish initialization of that field as part of the constructor. Otherwise you will have to synchronize on a lock before using it. This is part of the Java language definition.

    Here's another couple references:

    • Double check locking is broken
    • Synchronization and the Java Memory Model
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题