Java Concurrency Interview

Atomics and compare-and-swap question 61 of 180 senior

What is the difference between compareAndSet and weakCompareAndSet?

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.

cas atomics

Quiz yourself on Atomics and compare-and-swap Suggest a correction