Skip to content
javahacks.dev
Concurrency

Java Atomic LongAdder and AtomicInteger for Safe Counters

Use AtomicInteger, AtomicLong and LongAdder for thread safe counters in Java: compareAndSet, updateAndGet, contention behaviour and which class to choose.

6 min read
Summarize in AI
Flat illustration of threads sharing work across lanes, a lock and a pool, with the OpenJDK, IntelliJ IDEA, Linux and Apache Maven logos.

The most common concurrency bug is also the smallest: two threads incrementing a shared counter.

The lost update

java
class Hits {
    private int count;
    void hit() { count++; }          // read, add, write: three steps
}

Two threads read 5, both write 6, and one increment is gone. Declaring the field volatile fixes visibility and not atomicity, as the comparison in volatile versus synchronized shows.

AtomicInteger and AtomicLong

java
class Hits {
    private final AtomicLong count = new AtomicLong();
    void hit() { count.incrementAndGet(); }
    long total() { return count.get(); }
}

These classes use a hardware compare-and-swap instruction in a loop. The usual methods:

MethodDoes
incrementAndGet(), getAndIncrement()Add one, return new or old value
addAndGet(n)Add n
compareAndSet(expected, update)Set only if the current value equals expected
updateAndGet(f), accumulateAndGet(x, f)Apply a function atomically
getAndSet(v)Replace and return the old value

compareAndSet is the building block for a lock-free update: read, compute, try to swap, retry on failure. A bounded counter shows it:

java
boolean tryAcquire(AtomicInteger permits) {
    while (true) {
        int current = permits.get();
        if (current == 0) return false;
        if (permits.compareAndSet(current, current - 1)) return true;
    }
}

updateAndGet(c -> c == 0 ? 0 : c - 1) expresses a similar loop in one call. The function may run more than once under contention, so it must be free of side effects.

LongAdder for hot counters

An AtomicLong serializes writers on a single memory location. Under heavy contention from many threads, the compare-and-swap retries burn CPU. LongAdder keeps several cells, and each thread updates its own, and sum() adds them up.

java
class RequestMetrics {
    private final LongAdder requests = new LongAdder();
    void onRequest() { requests.increment(); }
    long snapshot() { return requests.sum(); }
}

The price is a value that is not instantaneous: sum() reads cells while writers continue, so it is exact only when writes pause. That is fine for metrics and bad for a sequence generator. LongAccumulator generalizes it to max or min.

NeedClass
Unique ids, exact reads, CASAtomicLong
High-volume statisticsLongAdder
Max or min across threadsLongAccumulator
A flagAtomicBoolean
A reference to an immutable snapshotAtomicReference<T>

Do not compose atomics

java
if (balance.get() >= amount) {
    balance.addAndGet(-amount);       // another thread may have spent it between the two lines
}

Each call is atomic, and the pair is not. Either use compareAndSet in a loop, put both steps under a lock, or keep the related fields in one immutable object:

java
record State(long balance, int version) { }
AtomicReference<State> state = new AtomicReference<>(new State(100, 0));

state.updateAndGet(s -> new State(s.balance() - 10, s.version() + 1));

Several fields that must change together belong in one object swapped atomically, or behind a lock, the topic of ReentrantLock.

When a plain lock is better

If the critical section does more than one counter update, or the contention is low, synchronized is just as fast and easier to read. The mechanics are in synchronized blocks. Measure before replacing locks with atomics for performance, with a harness like JMH, since the result depends on core count and contention.

Measure the cost of contention

The advice to use LongAdder for hot counters is a claim about contention, and contention is easy to measure. This program has eight threads increment one counter 20 million times each, using AtomicLong, LongAdder and a synchronized block, on Eclipse Temurin 25.0.5 in a container with 10 CPUs. Each implementation is checked for lost updates.

Adder.javajava
AtomicLong al = new AtomicLong();
LongAdder la = new LongAdder();
Object lock = new Object(); long[] box = {0};

run(() -> al.incrementAndGet(), threads, per);
run(() -> la.increment(), threads, per);
run(() -> { synchronized (lock) { box[0]++; } }, threads, per);
Text
round 1  AtomicLong  8611 ms | LongAdder   193 ms | synchronized  1803 ms
round 2  AtomicLong  9281 ms | LongAdder   175 ms | synchronized  1751 ms

For 160 million increments in total, LongAdder finished in about 0.18 seconds, the lock took about 1.8 seconds, and AtomicLong took about 9 seconds, nearly fifty times slower than the adder. The result runs against a common assumption that lock-free means fastest. Under heavy contention every incrementAndGet is a compare-and-swap on one cache line, threads retry whenever they lose, and the line bounces between cores. LongAdder spreads updates over several cells, one per contending thread, and adds them up only when you read. The price is that reads are more expensive and not a single atomic snapshot: sum() walks the cells while updates continue.

All three kept the total exact. A plain int with no protection, run with eight threads and 1,000,000 increments each, ended at 1,660,770 instead of 8,000,000. That row is the starting point of the lost update problem the first section describes.

Which one to use

NeedUse
a counter updated by many threads and read occasionally (metrics, hit counts)LongAdder
a value updated by few threads, or read and compared as often as writtenAtomicLong, AtomicInteger
a counter whose value decides what happens next (a sequence number, a limit)AtomicLong, because you need the exact value atomically with the update
several fields that must change togethera lock, or an immutable object in an AtomicReference

The deciding question is whether you need the precise value at the same instant as the increment. A request counter for a dashboard does not: nobody cares if the number is off by a few for a millisecond. A ticket number does, and giving two callers the same number is a bug that incrementAndGet prevents and LongAdder.sum() cannot. LongAccumulator generalises the adder to any commutative function, such as a running maximum.

java
LongAccumulator maxLatency = new LongAccumulator(Long::max, Long.MIN_VALUE);
requests.forEach(r -> maxLatency.accumulate(r.latencyMillis()));
System.out.println(maxLatency.get());

Reset and read carefully

LongAdder.reset() and sumThenReset() are not atomic with concurrent updates. An increment that arrives during the reset can be lost or counted twice, depending on timing. Use sumThenReset() for interval metrics where an occasional boundary error is acceptable. When exactness matters, keep a counter that only grows and compute the difference between two reads.

java
long previous = 0;
void report(LongAdder total) {
    long now = total.sum();
    log.info("requests in the last interval: {}", now - previous);
    previous = now;
}

This pattern also survives restarts of the reporting code, since the counter itself is never touched. Frameworks do it for you: Micrometer's Counter uses a DoubleAdder or LongAdder internally and exposes the monotonically increasing total, and the monitoring system takes the rate.

Retire the lock-based counter on purpose

Replacing an old synchronized counter is a refactoring, and it deserves a test that proves nothing was lost. The plain int run in this post is the test's negative control: eight threads adding 1,000,000 each produced 1,660,770 and not 8,000,000. A test that runs the same harness against the replacement and asserts the exact total fails for the wrong implementation and passes for the right one, so it protects the change.

java
@Test
void noUpdatesAreLost() throws Exception {
    LongAdder counter = new LongAdder();
    ExecutorService pool = Executors.newFixedThreadPool(8);
    List<Future<?>> done = new ArrayList<>();
    for (int t = 0; t < 8; t++) done.add(pool.submit(() -> { for (int i = 0; i < 100_000; i++) counter.increment(); }));
    for (Future<?> f : done) f.get();
    pool.shutdown();
    assertEquals(800_000, counter.sum());
}

Read sum() only after all writers have finished, as the test does. Reading while writers run gives a value that is correct for some instant but not a particular one, which is by design.

Where this does not apply

Atomics make single variables safe. They say nothing about the memory visibility of other fields, except through their happens-before guarantees, described in the Java memory model. The reference is the [java.util.concurrent.atomic package summary](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/atomic/package-summary.html), and the [LongAdder Javadoc](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/atomic/LongAdder.html) explains the cells.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.