2010-11-12 58 views
3
static boolean unsynchronizedSetter(Date expected){ 
    Date newDate = new Date(); 
    AtomicReference<Date> myAtomicReference = Lookup.getAtomicRef(); 
    boolean myStatus = myAtomicReference.compareAndSet(expected, newDate); //CAS 
    return myStatus; 
} 

問:如果2個線程執行它,哪個對象將存儲在原子引用?2個線程執行myAtomicReference.compareAndSet(預計,新的日期())

在多處理器機器中,2個線程可能在相同的時鐘週期內執行CAS。假設它們都使用相同的myAtomicReference對象來執行CAS,它們都使用「expected」的正確值,但它們試圖放入2個不同的對象,即2個newDate。其中一個必須失敗,但myStatus會在該線程中爲假?

我猜想CompareAndSwap的一個硬件實現會使線程排隊以進行更新。我猜即使2個處理器在相同的時鐘週期內執行CAS指令,其中一個可能會延遲。

回答

1
Q: If 2 threads executes it, which object will get stored in the atomic reference? 

沒有人知道。根據javadoc,其中之一。

In a multi-processor machine, 2 threads could be performing the CAS in the same clock cycle. 

AFAIK,目前英特爾/ AMD多核CPU沒有全局時鐘。

One of them must fail, but will myStatus be false in that thread? 

它一定是,否則就意味着它成功了,整個java.util.concurrent會崩潰。我很確定,一個線程中的myStatus必須是假的,即使兩者都試圖放置相同的對象。

I guess one hardware implementation of CompareAndSwap would make the threads queue up to do their updates. 

我不會說「排隊」(這聽起來像是由操作系統完成的),CAS指令將被硬件延遲。

1

感謝您的意見。由於原來的提問,我現在覺得它可能是myStatus == true在兩個線程 - 這是我的初步答案,下面

"One of them must fail, but will myStatus be false in that thread?" 

這是可以想象的,恕我直言,我自己的問題,這兩個線程「思考」,他們成功地把在他們各自的newDate對象中。然而,第一個線程應該知道它的變量myStatus在CAS操作之後的整個時間是無可救藥的不可靠的。這是不可靠的,因爲myStatus可能是真的,但是當你閱讀AtomicReference時,它的值可能已經改變。任何線程都可以隨時更改共享的AtomicReference。這個AtomicReference實例不受任何同步構造的保護。

myStatus==true僅意味着此線程對expected的值有正確的猜測,因此JVM必須爲正確的猜測給予它承諾的獎勵。但是,JVM不會將newDate保留在AtomicReference中。因此贏得這個「獎」意味着什麼。

我希望這是有道理的。