2013-07-06 45 views
4

我只是想知道下面的重新排序是否有效的一個或不在新的JMM模型有效的重新排序 - 在新的JMM

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 

上面的代碼可以重新爲以下處決。

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 

另一種情況:

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 
    } 

另一種情況:

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 
    } 

另一種情況:

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 

做到以上4​​例在原代碼的有效重新排序新的JMM模型。 我已經給所有基於我的 http://gee.cs.oswego.edu/dl/jmm/cookbook.html

回答

1

理解上面的重新排序考慮如何正常負載/存儲與顯示器重新排序進入和退出:

案例1個重新排序正常加載/存儲與顯示器輸入哪一個是有效的重新排序。

情況2使用監視器進入正常加載/存儲和監視器出口,然後是正常加載/存儲,這是有效的重新排序。

查看相似例子:Roach Motels and Java Memory Model。這表明訪問可以移動到同步塊中,但不會再退出。

情況3和4對監視器進行重新排序,後面跟着一個無效的正常加載/存儲。