Atomic classes

The classes in java.util.concurrent.atomic update a single value safely from many threads without locks. They rely on one hardware instruction, compare-and-set, which changes a value only if it still holds what you expect. This page explains that instruction and the retry loop built on it, then shows the traps it creates (update functions that run twice, and the ABA problem), the array and field-updater variants, and measures when LongAdder beats AtomicLong.

Contents

Compare-and-set: the instruction underneath

A counter shared by threads needs count++ to be one indivisible step, but it is three: read, add, write. A lock makes the three steps exclusive. The atomic classes use a different approach, built on a CPU instruction called compare-and-set (CAS; lock cmpxchg on x86): "if this memory location still holds the value I expect, replace it with my new value, and tell me whether that worked". The check and the write happen as one hardware operation, so no other thread can slip in between.

Any update can be built from CAS with a retry loop: read the current value, compute the new value, try to CAS it in, and if another thread changed the value in the meantime, start again with the fresh value. No thread ever waits for a lock, which is why these algorithms are called lock-free. Under heavy contention many attempts fail and retry, and that is the cost the last section measures.

Every atomic class also has the memory effects of a volatile field: a write is visible to all later reads, as explained on the Java Memory Model page.

The java.util.concurrent.atomic classes
ClassSinceHoldsBest for
AtomicInteger, AtomicLong, AtomicBooleanJava 5One number or flagCounters, ids, state flags
AtomicReference<V>Java 5One object referenceSwapping immutable state as a whole
AtomicIntegerArray, AtomicLongArray, AtomicReferenceArrayJava 5An array of atomic slotsHistograms, per-bucket counters
AtomicIntegerFieldUpdater and the long and reference versionsJava 5Nothing; they update a volatile field of other objectsMany objects that each need one atomic field
AtomicStampedReference, AtomicMarkableReferenceJava 5A reference plus an int stamp or a booleanAvoiding the ABA problem
LongAdder, DoubleAdder, LongAccumulator, DoubleAccumulatorJava 8A value spread over several cellsCounters and maximums updated by many threads, read rarely

Java 9 added weaker access modes to the classes, such as getAcquire, setRelease and weakCompareAndSetPlain, matching VarHandle. Application code rarely needs them. The programs on this page were run on JDK 21 on a 2-CPU machine.

The main methods

An AtomicInteger starting at 5 goes through each kind of update, chosen so that the difference between methods that return the old value and those that return the new one is visible.

Java
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class AtomicBasics {

    record Range(int low, int high) {
    }

    public static void main(String[] args) {
        AtomicInteger n = new AtomicInteger(5);
        System.out.println("incrementAndGet: " + n.incrementAndGet());   // 6, returns new value
        System.out.println("getAndIncrement: " + n.getAndIncrement());   // 6, returns old value
        System.out.println("now:             " + n.get());               // 7
        System.out.println("addAndGet(10):   " + n.addAndGet(10));
        System.out.println("updateAndGet(x*2): " + n.updateAndGet(x -> x * 2));
        System.out.println("accumulateAndGet(50, max): " + n.accumulateAndGet(50, Math::max));

        // compareAndSet: change only if the current value is what we expect
        System.out.println("CAS 50 -> 0: " + n.compareAndSet(50, 0) + ", value " + n.get());
        System.out.println("CAS 50 -> 1: " + n.compareAndSet(50, 1) + ", value " + n.get());

        // AtomicReference: swap a whole immutable object atomically
        AtomicReference<Range> range = new AtomicReference<>(new Range(0, 10));
        Range widened = range.updateAndGet(r -> new Range(r.low(), r.high() + 5));
        System.out.println("range: " + widened);
    }
}

Output:

Output
incrementAndGet: 6
getAndIncrement: 6
now:             7
addAndGet(10):   17
updateAndGet(x*2): 34
accumulateAndGet(50, max): 50
CAS 50 -> 0: true, value 0
CAS 50 -> 1: false, value 0
range: Range[low=0, high=15]
  • incrementAndGet returned 6, the new value; getAndIncrement also returned 6, the old value, and left 7. Every update comes in both forms, so pick the one whose return value you need.
  • updateAndGet(x -> x * 2) turned 17 into 34, and accumulateAndGet(50, Math::max) combined 34 with 50 to give 50. These Java 8 methods run the CAS loop for you with any function.
  • compareAndSet(50, 0) succeeded because the value was 50. The second CAS expected 50 again, found 0, changed nothing and returned false. This boolean is how lock-free code learns that another thread got there first.
  • AtomicReference.updateAndGet replaced the whole Range record with a new one. With immutable objects, swapping the reference updates both fields together, something two separate atomic fields could not do.

The compare-and-set loop by hand

Writing the loop yourself shows what incrementAndGet and updateAndGet do inside. Four threads each add 1 to a counter 250,000 times through the hand-written loop, which also counts its failed attempts.

Java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class CasLoop {

    // What incrementAndGet does inside: read, compute, try to swap, retry if someone else won
    static int increment(AtomicInteger value, AtomicInteger retries) {
        while (true) {
            int current = value.get();
            int next = current + 1;
            if (value.compareAndSet(current, next)) {
                return next;
            }
            retries.incrementAndGet();            // another thread changed it first: try again
        }
    }

    public static void main(String[] args) throws InterruptedException {
        AtomicInteger counter = new AtomicInteger();
        AtomicInteger retries = new AtomicInteger();
        ExecutorService pool = Executors.newFixedThreadPool(4);
        for (int t = 0; t < 4; t++) {
            pool.submit(() -> {
                for (int i = 0; i < 250000; i++) {
                    increment(counter, retries);
                }
            });
        }
        pool.shutdown();
        pool.awaitTermination(1, TimeUnit.MINUTES);
        System.out.println("counter: " + counter.get() + " (expected 1000000)");
        System.out.println("CAS retries: " + (retries.get() > 0 ? "some" : "none")
                + "; no lock was ever taken");
    }
}

Output:

Output
counter: 1000000 (expected 1000000)
CAS retries: some; no lock was ever taken
  • The counter reached exactly 1,000,000 with no lock. Every increment either won its CAS or retried with the newer value; none was lost.
  • Some attempts failed and retried. How many depends on timing and changes every run, which is why the program prints only whether there were any. On x86 the JIT compiles incrementAndGet to a single lock xadd instruction that cannot fail, so the built-in method does not even need this loop; for arbitrary functions, the loop is the general technique.

Trap: the update function may run more than once

Because updateAndGet retries when its CAS fails, the function you pass can be called several times for a single update. To make that happen on every run, this program has another thread add a pen to a shared cart while the first call of the update function is still running.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class RetriedUpdate {

    record Cart(List<String> items, int total) {
        Cart add(String item, int price) {
            List<String> copy = new ArrayList<>(items);
            copy.add(item);
            return new Cart(List.copyOf(copy), total + price);   // a new immutable value
        }
    }

    public static void main(String[] args) throws InterruptedException {
        AtomicReference<Cart> cart = new AtomicReference<>(new Cart(List.of(), 0));
        AtomicInteger calls = new AtomicInteger();

        // The update function is called again if another thread changed the value meanwhile
        Cart result = cart.updateAndGet(c -> {
            if (calls.incrementAndGet() == 1) {
                interfere(cart);                                  // force a conflict once
            }
            System.out.println("  function call " + calls.get() + " sees " + c);
            return c.add("book", 12);
        });
        System.out.println("result:            " + result);
        System.out.println("function was called " + calls.get() + " times for one update");
    }

    // Another thread adds an item between our read and our compare-and-set
    static void interfere(AtomicReference<Cart> cart) {
        Thread other = new Thread(() -> cart.updateAndGet(c -> c.add("pen", 2)));
        other.start();
        try {
            other.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

Output:

Output
function call 1 sees Cart[items=[], total=0]
  function call 2 sees Cart[items=[pen], total=2]
result:            Cart[items=[pen, book], total=14]
function was called 2 times for one update
  • The first call saw an empty cart and built a cart with just the book. Its CAS then failed, because the other thread had already replaced the cart with one holding the pen. The function was called a second time with the pen cart, and that result won: pen and book, total 14.
  • Nothing was lost, which is the point of the loop. But the function ran twice, so it must be free of side effects. Sending an email, writing a log line that matters or incrementing another counter inside it can happen more than once. The Javadoc says it directly: the function should be side-effect-free, since it may be re-applied when attempted updates fail.
  • The cart is an immutable record and each call builds a new one with List.copyOf, so a discarded attempt left no trace. Mutating the old cart inside the function would have changed it even on a failed attempt.

The ABA problem

CAS compares values, not history. If another thread changes a value from A to B and back to A between your read and your CAS, the CAS succeeds as if nothing happened. For a counter that is harmless; for a lock-free stack, where A is a node that was removed and reinserted, it can corrupt the structure. The program forces that sequence with a second thread and compares a plain reference with a stamped one.

Java
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

public class AbaProblem {

    public static void main(String[] args) throws InterruptedException {
        String a = "A";
        String b = "B";

        // Plain AtomicReference: A -> B -> A by another thread is invisible to CAS
        AtomicReference<String> ref = new AtomicReference<>(a);
        String seen = ref.get();                               // we read A ...
        run(() -> {
            ref.set(b);                                        // ... someone changes it to B
            ref.set(a);                                        // ... and back to A
        });
        System.out.println("AtomicReference CAS A->C succeeds: " + ref.compareAndSet(seen, "C")
                + "  (it never noticed the change)");

        // AtomicStampedReference: a version number travels with the reference
        AtomicStampedReference<String> stamped = new AtomicStampedReference<>(a, 0);
        int[] stampHolder = new int[1];
        String seenS = stamped.get(stampHolder);
        int seenStamp = stampHolder[0];
        run(() -> {
            stamped.set(b, stamped.getStamp() + 1);
            stamped.set(a, stamped.getStamp() + 1);
        });
        boolean ok = stamped.compareAndSet(seenS, "C", seenStamp, seenStamp + 1);
        System.out.println("AtomicStampedReference CAS A->C succeeds: " + ok
                + "  (stamp moved from " + seenStamp + " to " + stamped.getStamp() + ")");
    }

    static void run(Runnable r) throws InterruptedException {
        Thread t = new Thread(r);
        t.start();
        t.join();
    }
}

Output:

Output
AtomicReference CAS A->C succeeds: true  (it never noticed the change)
AtomicStampedReference CAS A->C succeeds: false  (stamp moved from 0 to 2)
  • The AtomicReference CAS from A to C succeeded, although the value had been changed twice in between. Any decision made from the earlier read could now be wrong.
  • AtomicStampedReference stores a version number with the reference, and the other thread increased it with each change, from 0 to 2. The CAS expected stamp 0 and failed, so the change was detected.
  • In Java, ABA matters much less than in C, because the garbage collector never reuses the memory of an object that is still referenced; most code that compares immutable values is safe. It does matter when the same object can genuinely return, as with node reuse or pooling.

Atomic arrays, field updaters and accumulators

Three more tools cover cases a single atomic value does not: many independent counters in one array, one atomic field in each of thousands of objects, and a running maximum. Random values in the histogram vary between runs, so the program prints only totals that are fixed.

Java
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.LongAccumulator;

public class ArraysAndUpdaters {

    // A field updater works on a volatile int field of many objects: no AtomicInteger per object
    static class Node {
        volatile int visits;
        int plainField;
    }

    static final AtomicIntegerFieldUpdater<Node> VISITS =
            AtomicIntegerFieldUpdater.newUpdater(Node.class, "visits");

    public static void main(String[] args) throws InterruptedException {
        // 1. AtomicIntegerArray: each slot is updated atomically on its own
        AtomicIntegerArray histogram = new AtomicIntegerArray(10);
        LongAccumulator max = new LongAccumulator(Math::max, Long.MIN_VALUE);
        Thread[] ts = new Thread[4];
        for (int t = 0; t < ts.length; t++) {
            ts[t] = new Thread(() -> {
                ThreadLocalRandom rnd = ThreadLocalRandom.current();
                for (int i = 0; i < 25000; i++) {
                    int v = rnd.nextInt(100);
                    histogram.incrementAndGet(v / 10);         // bucket 0..9
                    max.accumulate(v);
                }
            });
            ts[t].start();
        }
        for (Thread t : ts) {
            t.join();
        }
        int total = 0;
        for (int i = 0; i < histogram.length(); i++) {
            total += histogram.get(i);
        }
        System.out.println("histogram total: " + total + " (4 threads x 25,000)");
        System.out.println("LongAccumulator max: " + max.get());

        // 2. A field updater on 1,000 nodes
        Node[] nodes = new Node[1000];
        for (int i = 0; i < nodes.length; i++) {
            nodes[i] = new Node();
        }
        Thread a = new Thread(() -> visitAll(nodes));
        Thread b = new Thread(() -> visitAll(nodes));
        a.start();
        b.start();
        a.join();
        b.join();
        long sum = 0;
        for (Node n : nodes) {
            sum += n.visits;
        }
        System.out.println("visits counted through the updater: " + sum + " (2 x 1,000 x 100)");

        // 3. The field must be volatile, an int, and accessible
        try {
            AtomicIntegerFieldUpdater.newUpdater(Node.class, "plainField");
        } catch (IllegalArgumentException e) {
            System.out.println("updater on a non-volatile field: IllegalArgumentException: "
                    + e.getMessage());
        }
    }

    static void visitAll(Node[] nodes) {
        for (int round = 0; round < 100; round++) {
            for (Node n : nodes) {
                VISITS.incrementAndGet(n);
            }
        }
    }
}

Output:

Output
histogram total: 100000 (4 threads x 25,000)
LongAccumulator max: 99
visits counted through the updater: 200000 (2 x 1,000 x 100)
updater on a non-volatile field: IllegalArgumentException: Must be volatile type
  • The histogram counted all 100,000 values across its 10 slots. An AtomicIntegerArray gives each slot volatile, atomic semantics; an AtomicInteger[] would work too, but needs a separate object per slot.
  • LongAccumulator(Math::max, Long.MIN_VALUE) tracked the largest value, 99, the highest that nextInt(100) can return. The function must be associative and side-effect-free, because the accumulator applies it to cells in any order.
  • The field updater incremented the visits field of 1,000 nodes to a total of 200,000, without an AtomicInteger object per node. With millions of nodes, that saves an object header and a reference per node. The JDK applies the same idea, an atomic field instead of an atomic object, inside CompletableFuture through VarHandle.
  • Creating an updater for a non-volatile field failed with "Must be volatile type". The field must also be an int (or long, or a reference for the matching updater) and accessible from the class that creates the updater.

LongAdder versus AtomicLong

An AtomicLong is a single memory location, so every increment from every core competes for the same cache line. A LongAdder starts the same way but, when its CAS fails because of contention, it adds cells and lets different threads update different cells; sum() adds them up. Sixteen million increments are split over 1, 2 and 8 threads, each case run 3 times with the fastest reported. This is a rough comparison, not a benchmark.

Java
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

public class LongAdderVsAtomic {

    static long run(Runnable increment, int threads, int total) throws InterruptedException {
        long best = Long.MAX_VALUE;
        for (int r = 0; r < 3; r++) {
            Thread[] ts = new Thread[threads];
            for (int t = 0; t < threads; t++) {
                ts[t] = new Thread(() -> {
                    for (int i = 0; i < total / threads; i++) {
                        increment.run();
                    }
                });
            }
            long t0 = System.nanoTime();
            for (Thread t : ts) {
                t.start();
            }
            for (Thread t : ts) {
                t.join();
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        return best / 1000000;
    }

    public static void main(String[] args) throws InterruptedException {
        int total = 16000000;
        System.out.printf("%,d increments in total, best of 3, %d CPUs%n",
                total, Runtime.getRuntime().availableProcessors());
        for (int threads : new int[] {1, 2, 8}) {
            AtomicLong atomic = new AtomicLong();
            LongAdder adder = new LongAdder();
            long atomicMs = run(atomic::incrementAndGet, threads, total);
            long adderMs = run(adder::increment, threads, total);
            System.out.printf("%d thread(s): AtomicLong %,5d ms   LongAdder %,5d ms"
                    + "   (both counted %s)%n", threads, atomicMs, adderMs,
                    atomic.get() == adder.sum() ? "the same" : "differently");
        }
    }
}

Output (rough timings on a 2-CPU Linux machine with JDK 21):

Output
16,000,000 increments in total, best of 3, 2 CPUs
1 thread(s): AtomicLong    79 ms   LongAdder   132 ms   (both counted the same)
2 thread(s): AtomicLong   407 ms   LongAdder    73 ms   (both counted the same)
8 thread(s): AtomicLong   540 ms   LongAdder    72 ms   (both counted the same)
  • With one thread there is no contention, and AtomicLong was faster: LongAdder does a little more work per increment.
  • With 2 or 8 threads, AtomicLong became several times slower than its single-thread time, because the cache line holding the value bounced between the cores and many CAS attempts failed. LongAdder stayed fast, as each thread mostly updated its own cell.
  • Both always reached the same total. The trade-off is on the reading side: sum() walks all cells, and the Javadoc notes it is not an atomic snapshot if updates happen during the call. There is also no incrementAndGet: a LongAdder cannot hand out unique ids. Use it for statistics that are written constantly and read occasionally.

Choosing an atomic class

Which tool for which shared value
SituationUse
Unique ids or a counter whose current value is read oftenAtomicLong.incrementAndGet()
A statistic incremented by many threads, read rarelyLongAdder
A running maximum or minimumLongAccumulator, or accumulateAndGet on an AtomicLong
Several fields that must change togetherAtomicReference to an immutable record, or a lock
A one-time switch such as "started"AtomicBoolean.compareAndSet(false, true)
One atomic field in very many objectsA field updater, or a VarHandle
Values that can return to an earlier stateAtomicStampedReference
Updates with side effects, or that must wait for a conditionA lock: see locks and conditions

See also synchronized and volatile for when a plain volatile field is enough, and ConcurrentHashMap for atomic per-key updates with merge and compute.