This depends on how the X
instance is published.
Suppose x
is published unsafely, eg. through a non-volatile
field
private X instance;
...
void someMethod() {
instance = new X();
}
Another thread accessing the instance
field is allowed to see a reference value referring to an uninitialized X
object (ie. where its constructor hasn't run yet). In such a case, its field x
would have a value of null
.
The above example translates to
temporaryReferenceOnStack = new memory for X // a reference to the instance
temporaryReferenceOnStack.<init> // call constructor
instance = temporaryReferenceOnStack;
But the language allows the following reordering
temporaryReferenceOnStack = new memory for X // a reference to the instance
instance = temporaryReferenceOnStack;
temporaryReferenceOnStack.<init> // call constructor
or directly
instance = new memory for X // a reference to the instance
instance.<init> // call constructor
In such a case, a thread is allowed to see the value of instance
before the constructor is invoked to initialize the referenced object.
Now, how likely this is to happen in current JVMs? Eh, I couldn't come up with an MCVE.
Bonus: Do I need to declare it volatile (I do not really care about
that value, it suffices that sometime in the future it will be the
newly assigned value and never is null)
Publish the enclosing object safely. Or use a final
AtomicReference
field which you set
.