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:

  1. the first conditional statement in the if(data == null) code
  2. 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.

  • 2
    It doesn’t seem like that, here’s the article of Shipilev 2014, the example was taken apart there ( SafeDCLFactory , only you’re missing the field). But you can remove volatile if you do one reading and the Data object is safely initialized (all its fields are final ). - zRrr
  • one
    a link to the report would be added, otherwise we don’t know which thesis is being analyzed - etki
  • I saw on jokere, I can’t add a link unfortunately ( - slippery
  • one
    According to JMM, different threads can observe a different execution order for the same actions, if the actions are not associated with the threads through happens-before. Those. the second stream can see w (supp, E) earlier than w (val, V) . - Roman
  • 2
    I will probably even add a quote : More specifically, if there is a relationship. It can be a question. - Roman

0