Quick revision
The short answer
Compare-and-set atomically compares a memory location with an expected value and writes a new value only if they match, reporting whether it wrote. On x86 the JIT compiles it to a single lock cmpxchg instruction, and on ARMv8 to a load-exclusive/store-exclusive loop or, on CPUs with the LSE extension, to a CAS instruction. weakCompareAndSet may fail spuriously even when the value matches, which lets it map to a single cheaper attempt on load-linked/store-conditional hardware, so it is meant for code that retries in a loop anyway.
What to remember
In this answer, we saw that compare-and-set compares and conditionally writes one memory location in a single indivisible step. On x86 it is lock cmpxchg, which takes exclusive ownership of the cache line and acts as a full barrier; on ARMv8 it is a load-exclusive/store-exclusive loop or an LSE CAS instruction. Java reaches it through atomic classes and VarHandles, which the JIT turns into those instructions as intrinsics. The weak variants may fail spuriously so they can map to a single attempt on some hardware, which is why they belong only in retry loops, and CAS-based algorithms in general retry rather than block.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Compare-and-set atomically compares a memory location with an expected value and writes a new value only if they match, reporting whether it wrote. On x86 the JIT compiles it to a single lock cmpxchg instruction, and on ARMv8 to a load-exclusive/store-exclusive loop or, on CPUs with the LSE extension, to a CAS instruction. weakCompareAndSet may fail spuriously even when the value matches, which lets it map to a single cheaper attempt on load-linked/store-conditional hardware, so it is meant for code that retries in a loop anyway.
Background to this question
Atomic classes, ConcurrentHashMap, the locks in java.util.concurrent and most lock-free libraries all rest on one primitive: compare-and-set. Knowing how it works down to the CPU explains why atomic counters stop scaling, why some methods are allowed to fail for no visible reason, and why lock-free code retries instead of waiting. In this answer, we will recap what CAS promises, look at how x86 and ARM implement it, follow it from AtomicInteger and VarHandle through the JIT, explain the weak variants and where they fit, and see how CAS-based algorithms make progress by retrying.
1What Compare-and-Set Promises
CAS takes three things: a memory location, the value we expect to find there, and the value we want to write. In one indivisible step it reads the location, compares it with the expected value, and writes the new value only if they are equal. It returns true if it wrote and false if it found something else. Indivisible means no other CPU core can write to that location between the compare and the write.
That one guarantee is enough to build counters, stacks, queues and locks. If a CAS fails, we know exactly why: someone else changed the value after we read it. So the natural response is to read again and retry.
2How x86 Does It
On x86 there is a single instruction, cmpxchg, that compares a register (the expected value) with memory and stores another register if they match. On its own it is not atomic across cores, so the JIT adds the lock prefix: lock cmpxchg. The lock prefix makes the core take exclusive ownership of the cache line holding the variable, perform the read, compare and write while no other core can touch that line, and then release it. It also acts as a full memory barrier, which is why a CAS on x86 also gives the strong ordering Java requires of compareAndSet.
Notice the cost model this implies. A CAS on a cache line that is already owned by the current core costs a few tens of cycles. A CAS on a line that another core just wrote must first pull the line across the chip, which can take a hundred cycles or more. That is why many threads doing CAS on one variable scale poorly, even though no thread ever blocks.
3How ARM Does It
ARMv8.0 has no single compare-and-swap instruction. Instead it has a pair: a load-exclusive (LDXR, or LDAXR with acquire ordering) reads the value and marks the address as reserved, and a store-exclusive (STXR or STLXR) writes only if the reservation is still intact, reporting success or failure. A CAS is built as a small loop: load-exclusive, compare, store-exclusive, and retry if the store-exclusive failed.
The store-exclusive can fail even if the value never changed, for example because another core wrote a different variable in the same cache line, or because of an interrupt. ARMv8.1 added the Large System Extensions (LSE) with real CAS and atomic add instructions such as CAS, CASAL and LDADD, which scale much better on servers with many cores. The JVM detects at startup whether the CPU supports LSE and uses those instructions when it does; recent ARM server CPUs such as AWS Graviton and Ampere support them.
| x86-64 | ARMv8 | |
|---|---|---|
| Instruction | lock cmpxchg | LDAXR/STLXR loop, or LSE CASAL |
| Can fail spuriously | No | LL/SC pair can; LSE CAS cannot |
| Ordering | Full barrier | Acquire/release variants chosen by JIT |
| Contended cost | Cache line transfer | Cache line transfer |
4From AtomicInteger to the Instruction
Java code never writes cmpxchg. AtomicInteger.compareAndSet calls an internal method of jdk.internal.misc.Unsafe, and AtomicReference and the newer code use a VarHandle, a typed handle to a field or array element introduced in Java 9 that offers compareAndSet, getAndAdd and other atomic modes on any field we choose. In both cases the JIT compiler treats the call as an intrinsic: instead of compiling a method call, it emits the CPU instruction directly at the call site.
So an atomic field costs one object header less than wrapping it in an AtomicInteger, and the operations are the same instructions. VarHandles are what the JDK itself uses inside classes such as ConcurrentHashMap and the locks package, and they are the supported replacement for sun.misc.Unsafe.
5WeakCompareAndSet and When to Use It
The weak variants, weakCompareAndSetVolatile, weakCompareAndSetAcquire, weakCompareAndSetRelease and weakCompareAndSetPlain on the atomic classes and VarHandles, have the same meaning as compareAndSet except for one thing: they are allowed to fail spuriously, that is, return false even when the value matched. Why would anyone want that? Because on load-linked/store-conditional hardware like ARMv8.0, the strong version must hide spurious store-exclusive failures with an inner retry loop, while the weak version can be a single attempt and let the caller's own loop handle the failure. Inside a loop that retries anyway, the weak version does the same job with less code.
So the rule is simple: use weak CAS only inside a retry loop, never for a one-shot decision such as 'did I win the race to initialise this?'. The JDK's own updateAndGet uses weakCompareAndSetVolatile inside its loop. One naming detail is worth knowing: on the atomic classes the old method called weakCompareAndSet only promised plain memory ordering, despite its name, so it was deprecated in Java 9 in favour of weakCompareAndSetPlain and weakCompareAndSetVolatile; check your version for its current status.
- Read the current value
- Compute the new value
- CAS succeeds?YesDoneNoChanged, or weak CAS failed spuriously: repeat
3 steps in order. Play them, or step through them one at a time.
Weak CAS fits here because a spurious failure only costs one more round of a loop we already have.
6Retrying Instead of Blocking
A lock makes losing threads wait. A CAS-based algorithm makes losing threads retry. That difference gives lock-free algorithms their main property: if one thread is paused or descheduled in the middle of an operation, it does not stop the others, because it holds nothing they are waiting for. Some thread's CAS always succeeds, so the system as a whole keeps making progress.
The cost is that under heavy contention the retries themselves are work, and the cache line holding the variable moves from core to core on every attempt. That is why the next tools in the toolbox, such as LongAdder and partitioned state, reduce how often threads touch the same variable rather than making the CAS faster.
7Follow-up questions
Does a successful CAS in Java also give memory visibility?
Yes. compareAndSet on an atomic class or a VarHandle has the memory effects of a volatile read and a volatile write, so everything a thread wrote before a successful CAS is visible to a thread that later reads the new value. The weak acquire, release and plain variants offer weaker ordering for specialists.
Is getAndIncrement implemented with CAS?
On x86 the JIT compiles getAndAdd to lock xadd, an atomic add that cannot fail, so there is no retry loop. On ARM with LSE it uses LDADD. Without LSE it becomes a load-exclusive/store-exclusive loop. The cache line contention is the same in all cases.
What happens if CAS keeps failing for one thread?
It keeps retrying. CAS loops are lock-free, not wait-free: the system always progresses, but an unlucky thread can in theory retry many times. In practice, with short operations, retries are few.
8Conclusion
In this answer, we saw that compare-and-set compares and conditionally writes one memory location in a single indivisible step. On x86 it is lock cmpxchg, which takes exclusive ownership of the cache line and acts as a full barrier; on ARMv8 it is a load-exclusive/store-exclusive loop or an LSE CAS instruction. Java reaches it through atomic classes and VarHandles, which the JIT turns into those instructions as intrinsics. The weak variants may fail spuriously so they can map to a single attempt on some hardware, which is why they belong only in retry loops, and CAS-based algorithms in general retry rather than block.
Open with
Compare-and-set takes a location, an expected value and a new value, and in one indivisible step it writes the new value only if the location still holds the expected one, returning whether it did.
Then, if they want more
On x86 the JIT emits lock cmpxchg: the lock prefix gives the core exclusive ownership of the cache line for the read-compare-write and acts as a full fence, which matches Java's volatile semantics for compareAndSet.
On ARMv8.0 there's no single instruction, so it's a load-exclusive, compare, store-exclusive loop, and on CPUs with the LSE extension, like Graviton, the JVM uses the CAS and CASAL instructions instead.
In Java we reach it through the atomic classes, which use an internal Unsafe, or through VarHandles, and the JIT treats those calls as intrinsics, so there's no method call, just the instruction. The weak variants, like weakCompareAndSetVolatile, are allowed to fail spuriously even when the value matches.
That lets them compile to a single load-linked, store-conditional attempt instead of an inner loop, so they're meant for code that already retries, like an updateAndGet loop, and never for a one-shot decision.
And that's the general model: CAS-based algorithms don't block; a losing thread re-reads and tries again, so a paused thread never holds up the others, but heavy contention on one variable still costs cache line transfers on every attempt.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 9
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.concurrent, package documentation, JLS chapter 17, Threads and Locks
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "How does compareAndSet work in hardware and in the JVM, and what is weakCompareAndSet for?": https://scrivio-interview-library.netlify.app/java/atomics/520976d58e/