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.

tanbin
  • 31
  • 2

2 Answers2

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

Nobody can know. According to the javadoc, one of them.

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

AFAIK, there's no global clock for current Intel/AMD multicore CPUs.

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

It must be, otherwise it'd mean that it succeeded and the whole java.util.concurrent would fall to pieces. I'm quite sure, that myStatus in one thread must be false even if both tried to put there the same object.

I guess one hardware implementation of CompareAndSwap would make the threads queue up to do their updates.

I wouldn't say "queue up" (this sounds like something done by the OS), the CAS instruction will be delayed by the hardware.

maaartinus
  • 44,714
  • 32
  • 161
  • 320
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.

cdeszaq
  • 30,869
  • 25
  • 117
  • 173
tanbin
  • 11
  • 1