I have a class Item
class Item {
public int count;
public Item(int count) {
this.count = count;
}
}
Then, I will put a reference to Item in a field of other class
class Holder {
public Item item;
public Holder() {
item = new Item(50);
}
}
Can this new Item object be safely published? If not, why? According to Java Concurrency in Practice, the new Item is published without being fully constructed, but in my opinion the new Item is fully constructed: its this
reference doesn't escape and the reference to it and its state is published at the same time, so the consumer thread will not see a stale value. Or is it the visibility problem. I don't exactly know the reason.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…