Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Concurrency

Atomic classes: AtomicInteger, AtomicReference and LongAdder

Reference for java.util.concurrent.atomic: AtomicInteger, AtomicLong, AtomicReference, compareAndSet, updateAndGet, LongAdder and when to prefer them.

The classes in java.util.concurrent.atomic give you single variables with thread-safe operations that do not use locks. They rely on hardware compare-and-swap (CAS) instructions: an update succeeds only if the variable still holds the value you expected, otherwise you retry. Because no thread ever blocks, atomics scale well under moderate contention and cannot deadlock.

The main types are AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference<V>, plus array versions (AtomicIntegerArray, ...) and accumulators (LongAdder, LongAccumulator) that are faster under heavy contention.

Java
AtomicInteger counter = new AtomicInteger();
counter.incrementAndGet();             // 1, atomically
counter.compareAndSet(1, 10);          // true: value was 1, is now 10

Try it

Java Counting without locks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java AtomicReference and a hand-written CAS loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public class AtomicInteger extends Number
public class AtomicReference<V>
public class LongAdder extends Number
Method Description
get(), set(v) Volatile read and write.
getAndSet(v) Sets the value and returns the previous one.
compareAndSet(expect, update) Sets to update only if the current value equals expect (== for references). Returns whether it succeeded.
incrementAndGet(), getAndIncrement(), decrementAndGet(), addAndGet(d), getAndAdd(d) Arithmetic updates (AtomicInteger, AtomicLong).
updateAndGet(fn), getAndUpdate(fn) Applies a function in a CAS loop. The function must be free of side effects since it may run more than once.
accumulateAndGet(x, fn) Combines the current value with x.
lazySet(v), getPlain(), getAcquire(), setRelease(v) Weaker memory orderings for experts.
LongAdder.add(x), increment(), sum(), reset() Striped counter; sum() is not an atomic snapshot while updates run.

Usage notes

  • Atomic does not mean composable. Each call is atomic, but "check then act" over two calls is not. if (n.get() < 10) n.incrementAndGet() can overshoot; use updateAndGet or compareAndSet in a loop.
  • Several variables need a lock. Atomics protect one variable. Invariants over two fields (a balance and a transaction count) need a lock or one immutable object in an AtomicReference.
  • AtomicReference.compareAndSet compares identity. Two equal but distinct objects do not match. Use the same instance you read.
  • ABA problem. A CAS cannot tell that a value changed from A to B and back to A. AtomicStampedReference and AtomicMarkableReference add a version number or flag.
  • LongAdder for hot counters. Under many writers it spreads updates across cells and beats AtomicLong; reading sum() is slower and only weakly consistent. Use AtomicLong when you need an exact value for decisions (sequence numbers).
  • Update functions must be pure. updateAndGet retries on contention, so side effects (logging, I/O) can happen more than once.
  • Memory effects. get/set act like volatile reads and writes; every successful CAS is a full synchronization point for that variable.
  • AtomicInteger is not an Integer. It has no equals/hashCode by value, so don't use it as a map key; it is mutable.