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++lock cmpxchg
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
| Class | Since | Holds | Best for |
|---|---|---|---|
AtomicIntegerAtomicLongAtomicBoolean | Java 5 | One number or flag | Counters, ids, state flags |
AtomicReference<V> | Java 5 | One object reference | Swapping immutable state as a whole |
AtomicIntegerArrayAtomicLongArrayAtomicReferenceArray | Java 5 | An array of atomic slots | Histograms, per-bucket counters |
AtomicIntegerFieldUpdater | Java 5 | Nothing; they update a volatile | Many objects that each need one atomic field |
AtomicStampedReferenceAtomicMarkableReference | Java 5 | A reference plus an int stamp or a boolean | Avoiding the ABA problem |
LongAdderDoubleAdderLongAccumulatorDoubleAccumulator | Java 8 | A value spread over several cells | Counters and maximums updated by many threads, read rarely |
Java 9 added weaker access modes to the classes, such as getAcquiresetReleaseweakCompareAndSetPlain
The main methods
An AtomicInteger
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:
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]
returned 6, the new value;incrementAndGet also returned 6, the old value, and left 7. Every update comes in both forms, so pick the one whose return value you need.getAndIncrement turned 17 into 34, andupdateAndGet(x -> x * 2) combined 34 with 50 to give 50. These Java 8 methods run the CAS loop for you with any function.accumulateAndGet(50, Math::max) 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.compareAndSet(50, 0) replaced the wholeAtomicReference.updateAndGet record with a new one. With immutable objects, swapping the reference updates both fields together, something two separate atomic fields could not do.Range
The compare-and-set loop by hand
Writing the loop yourself shows what incrementAndGetupdateAndGet
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:
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
to a singleincrementAndGet instruction that cannot fail, so the built-in method does not even need this loop; for arbitrary functions, the loop is the general technique.lock xadd
Trap: the update function may run more than once
Because updateAndGet
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:
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
, so a discarded attempt left no trace. Mutating the old cart inside the function would have changed it even on a failed attempt.List.copyOf
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.
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:
AtomicReference CAS A->C succeeds: true (it never noticed the change)
AtomicStampedReference CAS A->C succeeds: false (stamp moved from 0 to 2)
- The
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.AtomicReference 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.AtomicStampedReference- 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.
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:
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
gives each slot volatile, atomic semantics; anAtomicIntegerArray would work too, but needs a separate object per slot.AtomicInteger[] tracked the largest value, 99, the highest thatLongAccumulator(Math::max, Long.MIN_VALUE) can return. The function must be associative and side-effect-free, because the accumulator applies it to cells in any order.nextInt(100)- The field updater incremented the
field of 1,000 nodes to a total of 200,000, without anvisits 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, insideAtomicInteger throughCompletableFuture .VarHandle - Creating an updater for a non-volatile field failed with "Must be volatile type". The field must also be an
(orint , or a reference for the matching updater) and accessible from the class that creates the updater.long
LongAdder versus AtomicLong
An AtomicLongLongAddersum()
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):
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
was faster:AtomicLong does a little more work per increment.LongAdder - With 2 or 8 threads,
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.AtomicLong stayed fast, as each thread mostly updated its own cell.LongAdder - Both always reached the same total. The trade-off is on the reading side:
walks all cells, and the Javadoc notes it is not an atomic snapshot if updates happen during the call. There is also nosum() : aincrementAndGet cannot hand out unique ids. Use it for statistics that are written constantly and read occasionally.LongAdder
Choosing an atomic class
| Situation | Use |
|---|---|
| Unique ids or a counter whose current value is read often | AtomicLong.incrementAndGet() |
| A statistic incremented by many threads, read rarely | LongAdder |
| A running maximum or minimum | LongAccumulatoraccumulateAndGetAtomicLong |
| Several fields that must change together | AtomicReference |
| A one-time switch such as "started" | AtomicBoolean.compareAndSet(false, true) |
| One atomic field in very many objects | A field updater, or a |
| Values that can return to an earlier state | AtomicStampedReference |
| Updates with side effects, or that must wait for a condition | A lock: see |
See also volatilemergecompute