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

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指令,其中一个可能会被延迟。     
已邀请:
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,目前的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指令将被硬件延迟。     
感谢您的投入。作为最初的提问者,我现在觉得两个帖子中有可能是
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中。所以赢得那个“奖品”意味着什么。 我希望这是有道理的。     

要回复问题请先登录注册