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指令,其中一個可能會延遲。