Take the classic example:
public class Keeper { volatile Data data = null; public Data getData() { if(data == null) synchronized(this) { if(data == null) data = new Data(); } return data; } } As far as I understand this example is not entirely correct from the point of view of the JMM.
Namely, there occurs 2 readings of the volatile data variable after its creation:
- the first conditional statement in the
if(data == null)code - and
return data.
And if I correctly understood the report of Aleksey Shipilev, a situation may arise when, in the first reading, we read not null , and in the second reading there may be null . But unfortunately, I don’t quite understand why this can happen with a volatile variable.
Could you explain with proof why such a situation is possible.
Thank.
SafeDCLFactory, only you’re missing the field). But you can removevolatileif you do one reading and theDataobject is safely initialized (all its fields arefinal). - zRrr