2010-11-12 57 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中。因此赢得这个“奖”意味着什么。

我希望这是有道理的。