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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With