Skip to lesson

LongAdder for busy counters

An AtomicLong is correct under any number of threads, but when many threads update it at the same moment, they keep getting in each other's way. LongAdder solves this for counters and sums by letting threads add to different places and adding those places up only when you ask for the total.

Why many threads slow down one AtomicLong

Contention means many threads trying to change the same thing at the same time. With one AtomicLong, every thread does a CAS on the same memory location. Only one CAS per round can win; the others fail and retry.

Example 1 · More threads, same total, slower AtomicLong

ContentionDemo.javaJava
import java.util.concurrent.atomic.AtomicLong;
public class ContentionDemo {    static final long TOTAL = 16_000_000;
    static String run(int threadCount) throws InterruptedException {        AtomicLong hits = new AtomicLong();        long perThread = TOTAL / threadCount;        Thread[] threads = new Thread[threadCount];        long start = System.nanoTime();        for (int t = 0; t < threadCount; t++) {            threads[t] = new Thread(() -> {                for (long i = 0; i < perThread; i++) {                    hits.incrementAndGet();                }            }, "hits-" + (t + 1));            threads[t].start();        }        for (Thread t : threads) {            t.join();        }        long ms = (System.nanoTime() - start) / 1_000_000;        return threadCount + " thread(s): " + hits.get() + " hits in " + ms + " ms";    }
    public static void main(String[] args) throws InterruptedException {        run(1);                          // warm-up, so the JIT compiler has done its work        run(8);        System.out.println(run(1));        System.out.println(run(8));    }}
Sample output
1 thread(s): 16000000 hits in 46 ms
8 thread(s): 16000000 hits in 207 ms

What this code does

  • Both runs count the same 16 million hits and both totals are exact. Only the time differs.
  • With 8 threads, every increment fights for the same counter, so CAS retries and cache traffic make the work slower, not faster.
  • Timings change from run to run and from machine to machine, but on most multi-core computers the 8-thread run is not faster.

There is a hardware cost too. Each CPU core keeps a copy of recently used memory in its cache. When one core changes the counter, the copies in the other cores become invalid and the value has to travel between cores on almost every update. So adding more threads to a hot counter does not make counting faster. On most multi-core machines it makes it slower, even though the answer stays correct.

LongAdder keeps several cells and adds them up

LongAdder is a counter that spreads updates over several internal cells, so busy threads rarely collide. Its sum() method adds the cells up when you read the total.

LongAdder (in java.util.concurrent.atomic, since Java 8) keeps a base value plus, when threads collide, an array of cells. Each thread usually adds to its own cell, so threads rarely compete for the same memory.

Left, an AtomicLong has one cell: four threads T1 to T4 all update the same value and keep retrying. Right, a LongAdder has several cells: each thread updates a different cell, and sum() adds the cells up when you read the total.

Example 2 · LongAdder basics: add, sum, reset

LongAdderBasicsDemo.javaJava
import java.util.concurrent.atomic.LongAdder;
public class LongAdderBasicsDemo {    public static void main(String[] args) {        LongAdder likes = new LongAdder();        likes.increment();        likes.increment();        likes.add(10);        likes.decrement();        System.out.println("sum(): " + likes.sum());        System.out.println("intValue(): " + likes.intValue());        System.out.println("toString(): " + likes);
        long thisMinute = likes.sumThenReset();        System.out.println("sumThenReset() returned " + thisMinute + ", now " + likes.sum());
        likes.add(5);        likes.reset();        System.out.println("after reset(): " + likes.sum());    }}
Output
sum(): 11
intValue(): 11
toString(): 11
sumThenReset() returned 11, now 0
after reset(): 0

What this code does

  • increment(), decrement() and add(n) return nothing. That is the key difference from AtomicLong: you cannot get your own updated value back.
  • sum() gives the total; intValue() and toString() also use it.
  • sumThenReset() suits per-minute statistics: read the count for this minute and start the next one from zero.

Example 3 · Eight busy threads: AtomicLong versus LongAdder

AdderSpeedDemo.javaJava
import java.util.concurrent.atomic.AtomicLong;import java.util.concurrent.atomic.LongAdder;
public class AdderSpeedDemo {    static final int THREADS = 8;    static final int PER_THREAD = 2_000_000;
    static long time(Runnable increment) throws InterruptedException {        Thread[] threads = new Thread[THREADS];        long start = System.nanoTime();        for (int t = 0; t < THREADS; t++) {            threads[t] = new Thread(() -> {                for (int i = 0; i < PER_THREAD; i++) {                    increment.run();                }            }, "hits-" + (t + 1));            threads[t].start();        }        for (Thread t : threads) {            t.join();        }        return (System.nanoTime() - start) / 1_000_000;    }
    public static void main(String[] args) throws InterruptedException {        AtomicLong atomic = new AtomicLong();        LongAdder adder = new LongAdder();        time(atomic::incrementAndGet);           // warm-up runs        time(adder::increment);        atomic.set(0);        adder.reset();
        long atomicMs = time(atomic::incrementAndGet);        long adderMs = time(adder::increment);        System.out.println("AtomicLong: " + atomic.get() + " in " + atomicMs + " ms");        System.out.println("LongAdder:  " + adder.sum() + " in " + adderMs + " ms");    }}
Sample output
AtomicLong: 16000000 in 245 ms
LongAdder:  16000000 in 54 ms

What this code does

  • Both counters end at exactly 16,000,000. LongAdder is not less correct, only less crowded.
  • With LongAdder, threads mostly add to different cells, so they rarely retry and rarely fight over the same memory. On this run it was about four times faster.
  • The gap depends on the number of cores; on a two-core laptop it is much smaller.

You update it with increment(), decrement() or add(n). You read it with sum(), which adds the base and all the cells. reset() sets it to zero, and sumThenReset() reads and clears in one call. The price is memory and reading cost: the cells take more space than one long, and sum() has to visit every cell. That is a good trade for counters that are updated very often and read rarely, such as hits, likes or requests per minute.

sum() is not an exact snapshot

sum() is not atomic. It reads the cells one after another. If other threads are adding while it runs, some of their updates are counted and others are not, so the result is a value the counter may never have had at any single moment.

Example 4 · sum() while threads are still adding

SumWhileRunningDemo.javaJava
import java.util.concurrent.atomic.LongAdder;
public class SumWhileRunningDemo {    public static void main(String[] args) throws InterruptedException {        LongAdder requests = new LongAdder();        Thread[] servers = new Thread[4];        for (int s = 0; s < 4; s++) {            servers[s] = new Thread(() -> {                for (int i = 0; i < 5_000_000; i++) {                    requests.increment();                }            }, "server-" + (s + 1));            servers[s].start();        }
        for (int check = 1; check <= 3; check++) {            Thread.sleep(5);            System.out.println("Dashboard reading " + check + ": " + requests.sum());        }
        for (Thread t : servers) {            t.join();        }        System.out.println("After join: " + requests.sum());    }}
Sample output
Dashboard reading 1: 31893
Dashboard reading 2: 7054489
Dashboard reading 3: 13729615
After join: 20000000

What this code does

  • The three dashboard readings are taken while four threads are still adding. They change on every run and are only approximate totals.
  • sum() adds the cells one by one, so updates made during the reading may be partly included.
  • After join(), nobody is adding any more, and sum() gives the exact 20,000,000.

That is fine for monitoring: "about 12,40,000 requests so far" is useful while traffic flows. Once all updating threads have finished (for example after join()), sum() is exact. The same applies to sumThenReset(): an update that lands in the middle may be counted in this period or the next. Do not use it where every unit must be accounted for exactly while updates continue.

When AtomicLong is still the right choice

AtomicLong is still the right tool whenever a thread needs the value from its own update, or needs to compare and set it. LongAdder has no incrementAndGet() and no compareAndSet().

Example 5 · Token numbers need AtomicLong; the top bid fits LongAccumulator

AtomicLongStillRightDemo.javaJava
import java.util.TreeSet;import java.util.concurrent.atomic.AtomicLong;import java.util.concurrent.atomic.LongAccumulator;
public class AtomicLongStillRightDemo {    public static void main(String[] args) throws InterruptedException {        AtomicLong nextToken = new AtomicLong();        LongAccumulator topBid = new LongAccumulator(Long::max, Long.MIN_VALUE);        long[][] tokensTaken = new long[4][1000];
        Thread[] counters = new Thread[4];        for (int c = 0; c < 4; c++) {            int id = c;            counters[c] = new Thread(() -> {                for (int i = 0; i < 1000; i++) {                    tokensTaken[id][i] = nextToken.incrementAndGet();   // my own number                    topBid.accumulate(id * 1000 + i);                   // keep the maximum                }            }, "counter-" + (c + 1));            counters[c].start();        }        for (Thread t : counters) {            t.join();        }
        TreeSet<Long> unique = new TreeSet<>();        for (long[] row : tokensTaken) {            for (long token : row) {                unique.add(token);            }        }        System.out.println("Tokens handed out: " + unique.size() + " (all different)");        System.out.println("Lowest and highest token: " + unique.first() + " and " + unique.last());        System.out.println("Top bid: " + topBid.get());    }}
Output
Tokens handed out: 4000 (all different)
Lowest and highest token: 1 and 4000
Top bid: 3999

What this code does

  • Every caller needs its own token number, so the result of incrementAndGet() matters. LongAdder cannot give that; AtomicLong gives 4000 different tokens, 1 to 4000.
  • LongAccumulator keeps cells like LongAdder, but combines values with any function you give it, here Long::max.
  • Which counter got which token changes from run to run, but the set of tokens and the top bid are always the same.

Keep AtomicLong in these cases:

  • Unique numbers such as token, ticket or order IDs: incrementAndGet() gives each caller its own number.
  • Limits and checks: "stop at 500 registrations" needs getAndUpdate or a CAS loop.
  • Values read as often as they are written, or used by only a few threads: AtomicLong is simpler and uses less memory.
  • For a running maximum or minimum under heavy load, LongAccumulator is the LongAdder-style tool.

Next step

Check your understanding

12 quick questions