Atomic classes

Multithreading · lesson 5 of 38 · 3 min read

Do lock-free counters and updates with AtomicInteger, LongAdder and compare-and-set.

Open this lesson in the learning hub

Key points

  • AtomicInteger, AtomicLong and AtomicReference wrap one value and give it atomic read-modify-write operations.
  • They use a CPU compare-and-set instruction instead of a lock: read the value, swap it only if nobody else changed it, retry if they did.
  • incrementAndGet, getAndAdd, compareAndSet and updateAndGet cover nearly everything.
  • Under heavy contention prefer LongAdder. It spreads writes across several cells and adds them up only when you read.
  • Atomics protect one variable. If two fields must change together, you need a lock.

Example

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        AtomicInteger counter = new AtomicInteger();
        LongAdder adder = new LongAdder();

        Thread[] threads = new Thread[4];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                for (int n = 0; n < 100_000; n++) {
                    counter.incrementAndGet();   // lock-free CAS
                    adder.increment();           // striped, faster under contention
                }
            });
            threads[i].start();
        }
        for (Thread t : threads) t.join();

        System.out.println("AtomicInteger : " + counter.get());
        System.out.println("LongAdder     : " + adder.sum());

        AtomicInteger highScore = new AtomicInteger(5);
        highScore.accumulateAndGet(9, Math::max);   // retry-until-it-sticks, built in
        System.out.println("highScore     : " + highScore.get());
    }
}

One shared number? Use an atomic. Two that must agree? Use a lock.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Multithreading course, and every lesson in it is listed on the Multithreading contents page.