Java · OOP, JVM and backend craft

How do atomic classes work and when should you use them?

Mediumatomicscaslock-freeUpdated Oct 2026
Quiz this track

Short answer

Atomic classes provide lock-free thread-safe operations backed by compare-and-swap. They suit counters and single-variable updates, while LongAdder scales better under heavy contention.

AtomicInteger and AtomicReference use CAS: read the current value, compute a new one, and update only if the current value is still what was read. If another thread changed it, the operation retries. This avoids blocking but can spin under heavy contention.

java
AtomicInteger counter = new AtomicInteger();
counter.incrementAndGet();
counter.compareAndSet(1, 2);

LongAdder adder = new LongAdder();
adder.increment();
long total = adder.sum();
LongAdder spreads updates across cells and sums them, which scales better for statistics.

Choosing the right tool

  • AtomicInteger or AtomicLong for counters and sequence numbers
  • AtomicReference for lock-free replacement of an immutable object
  • AtomicReferenceArray or AtomicIntegerArray for indexed updates
  • LongAdder or DoubleAdder for high-contention statistics
  • VarHandle for advanced low-level access when the atomic classes are insufficient

CAS has an ABA problem: a value can change from A to B and back to A, so a compare succeeds even though the state changed. AtomicStampedReference adds a version stamp for cases where that matters, such as lock-free stacks.

An atomic variable protects one variable. It does not make a multi-field invariant atomic. For that, use a lock or encapsulate the state in one immutable object held in an AtomicReference.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is compare-and-swap?
  2. 2Why does LongAdder outperform AtomicLong under contention?
  3. 3What is the ABA problem?
  4. 4Can atomics replace locks for a multi-field invariant?

Say it in the interview

Atomic classes use compare-and-swap to update a value without blocking. The operation retries if another thread changed the value first. They are ideal for counters and single references, and LongAdder scales better for high-contention metrics by spreading updates across cells. They do not protect multi-field invariants, so I use a lock or one immutable state object when the update spans several fields.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.