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

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

In a multi-processor machine, 2 threads could be performing the CAS in the same clock cycle. Suppose they both use the same myAtomicReference object to do the CAS, both use the correct value of "expected", but they try to put in 2 distinct objects ie the 2 newDate. One of them must fail, but will myStatus be false in that thread?

I guess one hardware implementation of CompareAndSwap would make the threads queue up to do their updates. I guess even if the 2 processors are executing the CAS instruction in the same clock cycle, one of them is probably delayed.

4

2 回答 2

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,当前的 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指令将被硬件延迟。

于 2011-03-28T20:13:34.257 回答
1

Thanks for the input. As the original questioner, I now feel it's possible that myStatus == true in both threads -- this is my tentative answer to my own question below

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

It is conceivable, IMHO, that both threads "think" they succeeded in putting in their respective newDate object. However, the first thread should know that its variable myStatus is hopelessly unreliable the whole time, right after the CAS operation. It's unreliable because myStatus could be true but when you read the AtomicReference the value in it could have changed. The shared AtomicReference is subject to change any time by any thread. This AtomicReference instance is not guarded by any synchronization construct.

myStatus==true only means that this thread had a correct guess for the value of expected so JVM must give it the promised prize for the correct guess. However, JVM won't keep the newDate inside the AtomicReference. So winning that "prize" means nothing.

I hope this makes some sense.

于 2011-03-30T01:17:52.403 回答