Valid reorderings - under new JMM

前提是你 提交于 2019-12-10 15:59:51

问题


I just wanted to know whether the below reorderings are valid one or not under new JMM model

Original Code: 
     instanceVar1 = value ;//  normal read operation, no volatile
     synchronized(this) {
       instanceVar2 = value2; //normal read operation, no volatile   
     }
     instanceVar3 = value3;  //normal read operation, no volatile

The above code can be reordered into the following executions.

Case 1:

     synchronized(this) {
       instanceVar2 = value2; //normal read operation, no volatile   
       instanceVar1 = value ;//  normal read operation, no volatile
     }
     instanceVar3 = value3;  //normal read operation, no volatile

Another case :

Case 2:

  synchronized(this) {
       instanceVar3 = value3;  //normal read operation, no volatile
       instanceVar2 = value2; //normal read operation, no volatile   
       instanceVar1 = value ;//  normal read operation, no volatile
     }

Another Case :

Case 3: 

    instanceVar3 = value3;  //normal read operation, no volatile
    synchronized(this) {
       instanceVar2 = value2; //normal read operation, no volatile   
       instanceVar1 = value ;//  normal read operation, no volatile
     }

Another Case :

Case 4: 

    instanceVar3 = value3;  //normal read operation, no volatile
    synchronized(this) {
       instanceVar2 = value2; //normal read operation, no volatile   
     }
    instanceVar1 = value ;//  normal read operation, no volatile

Do all the above 4 cases are valid reordering of original Code under new JMM Model. I have given all the above reorderings based on my understanding of http://gee.cs.oswego.edu/dl/jmm/cookbook.html


回答1:


Consider how the normal load/stores are reordered with the monitor enter and exits:

Case 1 reorders a normal load/store with a monitor enter which is a valid reordering.

Case 2 reorders a normal load/store with a monitor enter, and a monitor exit followed by a normal load/store, which are valid reorderings.

See a similar example: Roach Motels and Java Memory Model. This shows that accesses can be moved into a synchronized block but not back out again.

Case 3 and 4 reorders a monitor enter followed by a normal load/store which is not valid.



来源:https://stackoverflow.com/questions/17505830/valid-reorderings-under-new-jmm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!