About reference to object before object's constructor is finished

后端 未结 4 589
感情败类
感情败类 2020-12-13 21:38

Every one of you know about this feature of JMM, that sometimes reference to object could receive value before constructor of this object is finish

4条回答
  •  余生分开走
    2020-12-13 22:07

    Construct exit plays an important role here; the JLS says "A freeze action on final field f of o takes place when c exits". Publishing the reference before/after constructor exit are very different.

    Informally

    1 constructor enter{
    
    2   assign final field
    
    3   publish this
    
    4 }constructor exit
    
    5 publish the newly constructed object
    

    [2] cannot be reordered beyond constructor exit. so [2] cannot be reordered after [5].

    but [2] can be reordered after [3].

提交回复
热议问题