Is this a safe publication of object?

前端 未结 2 1020
日久生厌
日久生厌 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

提交回复
热议问题