Atomics and compare-and-swap question 61 of 180 senior
What is the difference between compareAndSet and weakCompareAndSet?
weakCompareAndSetcompares withequals- Correct: The weak form may fail spuriously and has weaker ordering, which makes it cheaper on some architectures inside a loop that retries anyway
- The weak form skips the comparison and always writes
- The weak form does not use CAS at all
weakCompareAndSet is allowed to return false even when the value matched. On ARM and POWER, where
CAS is a load-linked / store-conditional pair, the store can fail for unrelated reasons such as an
intervening interrupt, and forcing a retry in hardware costs more than letting the caller retry.
It is only correct inside a loop that would retry anyway. Using it for a one-shot "set this flag if it is still null" is a bug, because a spurious failure is indistinguishable from a real one. On x86 the two compile to the same instruction, which is why testing on x86 proves nothing here.
One naming trap: on the atomic classes, the method called weakCompareAndSet has been deprecated since
Java 9, because the name never said which memory ordering it had. Use weakCompareAndSetPlain or
weakCompareAndSetVolatile, which do.
Quiz yourself on Atomics and compare-and-swap Suggest a correction