执行myAtomicReference.compareAndSet的2个线程(期望的,新的Date())

时间:2010-11-12 04:55:35

标签: optimistic-concurrency atomicreference

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个线程可以在相同的时钟周期内执行CAS。假设它们都使用相同的myAtomicReference对象来执行CAS,它们都使用正确的“预期”值,但是它们尝试放入2个不同的对象,即2个newDate。其中一个必须失败,但myStatus在该线程中是否会错误?

我想CompareAndSwap的一个硬件实现会让线程排队进行更新。我猜即使2个处理器在同一个时钟周期内执行CAS指令,其中一个可能会被延迟。

2 个答案:

答案 0 :(得分:1)

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

没有人能够知道。根据{{​​3}},其中之一。

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

AFAIK,目前的Intel / 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 :(得分:1)

感谢您的投入。作为最初的提问者,我现在觉得两个帖子中myStatus == true都有可能 - 这是我对下面我自己的问题的初步回答

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

可以想象,恕我直言,两个线程都“认为”他们成功地放入了各自的newDate对象。但是,在CAS操作之后,第一个线程应该知道它的变量myStatus在整个时间内是绝对不可靠的。这是不可靠的,因为myStatus可能是真的,但是当你读取AtomicReference时,它的值可能已经改变了。任何线程随时都可以更改共享的AtomicReference。任何同步构造都不保护此AtomicReference实例。

myStatus==true仅表示此线程对expected的值有正确猜测,因此JVM必须为其提供正确猜测的承诺奖励。但是,JVM不会将newDate保留在AtomicReference中。因此赢得“奖品”意味着什么。

我希望这是有道理的。