Atomics

A lock makes an increment safe, and it also makes the threads wait for each other. The atomic classes of java.util.concurrent.atomic do the same job with a single hardware instruction instead: a compare-and-swap that changes the value only if nobody else did, retried until it succeeds. This lesson runs the same race as lesson 115 through them, and the count is exact.

AtomicInteger

The four threads call incrementAndGet 250,000 times each and the counter is exactly a million, with no lock in the source:

import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.LongAdder; public class Atomics { public static void main(String[] args) throws InterruptedException { int threads = 4; int perThread = 250_000; AtomicInteger counter = new AtomicInteger(); run(threads, () -> { for (int i = 0; i < perThread; i++) { counter.incrementAndGet(); } }); System.out.println("atomic int: " + counter.get()); AtomicLong total = new AtomicLong(); run(threads, () -> total.addAndGet(perThread)); System.out.println("atomic long: " + total.get()); LongAdder adder = new LongAdder(); run(threads, () -> { for (int i = 0; i < perThread; i++) { adder.increment(); } }); System.out.println("long adder: " + adder.sum()); AtomicInteger max = new AtomicInteger(); run(threads, () -> { for (int i = 1; i <= 100; i++) { max.accumulateAndGet(i, Math::max); } }); System.out.println("max: " + max.get()); System.out.println("cas from 0: " + max.compareAndSet(0, 1000)); System.out.println("cas from max: " + max.compareAndSet(100, 1000)); System.out.println("after: " + max.get()); } static void run(int threads, Runnable task) throws InterruptedException { List<Thread> workers = new ArrayList<>(); for (int i = 0; i < threads; i++) { Thread worker = new Thread(task); workers.add(worker); worker.start(); } for (Thread worker : workers) { worker.join(); } } }

javac -Xlint:all Atomics.java
java Atomics

atomic int: 1000000
atomic long: 1000000
long adder: 1000000
max: 100
cas from 0: false
cas from max: true
after: 1000

LongAdder

All three counters reach a million, and they do it differently. AtomicInteger and AtomicLong keep one value and retry the swap when another thread got there first, which is fine until many threads hit the same variable: the retries turn into a queue of failed attempts. LongAdder keeps a cell per thread and sums them when sum is called, so the increments do not collide; the price is that sum walks the cells and is not a constant-time read.

A counter that is incremented far more often than it is read is a LongAdder, and a counter whose value is read as often as it is written is an AtomicLong. The second program of the lesson of the lost update is the shape this replaces: a field, a method and a lock become a single object with one call.

compareAndSet

compareAndSet(expected, update) writes the update only if the value is still the expected one, and answers whether it wrote. The two calls at the end show both outcomes: the first expected the value to be 0 and it was 100, so nothing happened, and the second expected 100 and succeeded, which is why the last line is 1000.

That single operation is what every other method of the class is built on, and it is the shape of a lock-free update: read the value, compute the new one, and try to install it; if somebody else changed it in between, read again and retry. A loop of that kind is correct without a lock, and it is what updateAndGet and accumulateAndGet run for you.

accumulateAndGet

The maximum needs a read, a comparison and a write, and doing it by hand would have the race of lesson 115 back. accumulateAndGet(value, Math::max) applies the function atomically, so four threads that each try the numbers 1 to 100 leave 100 and not a value from an interrupted comparison.

The same shape exists for an update with no argument, updateAndGet(n -> n + 1), and for a function of two arguments, getAndAccumulate, which answers the old value. A program that finds itself writing a loop with compareAndSet has usually found one of them that does it.

Which one to use

One counter or one flag: an AtomicInteger, AtomicLong or AtomicBoolean. A hot counter that is read rarely: a LongAdder. A value that is read and written together as a pair: AtomicReference of an immutable record, replaced by compareAndSet. Two pieces of state that must change together: a lock, because no atomic variable makes two writes one.

The last case is the one people get wrong. Two atomics updated one after the other are two operations and not one, and a reader may see the first new and the second old. The rule of lesson 115 applies to atoms as well: the unit of safety is the whole change, and a lock is the tool when the change has more than one field.

Exercises

  1. Run the atomic counter of Atomics with eight threads and the same per-thread count and print the total.
  2. Write a lock-free minimum with accumulateAndGet.
  3. Use AtomicReference of a record and replace it with compareAndSet from two threads.
  4. Explain in one sentence why two atomics cannot make a transfer of money atomic.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does incrementAndGet do without a lock?

    Answer

    A compare-and-swap loop that retries until it succeeds

    The hardware provides the swap, and the loop handles the case where another thread won.

  2. When is LongAdder better than AtomicLong?

    Answer

    When the counter is written much more often than it is read

    The per-thread cells remove the contention at the price of a slower sum.

  3. What does compareAndSet(a, b) answer?

    Answer

    Whether the value was a and is now b

    The boolean says whether the swap happened, and false means the value had changed.

  4. What does this program print? import java.util.concurrent.atomic.AtomicInteger; public class Q1 { public static void main(String[] args) { AtomicInteger value = new AtomicInteger(5); System.out.println(value.getAndIncrement()); System.out.println(value.get()); System.out.println(value.compareAndSet(6, 10)); System.out.println(value.get()); } }

    Answer

    5 / 6 / true / 10

    getAndIncrement answers the old value, and the swap from 6 to 10 succeeds.

  5. What is the unit of safety in a lock-free update?

    Answer

    One compare-and-swap, which changes one value if it is unchanged

    The swap is the only atomic step, so a change that spans two values still needs a lock.

  6. Why can two atomic variables not make a transfer atomic?

    Answer

    A reader may see the first updated and the second not yet

    Two swaps are two operations, and the invariant between them is not held.

  7. What does accumulateAndGet(x, f) do?

    Answer

    Atomically replaces the value with f(value, x) and answers the new value

    The function is applied inside the retry loop, so a read-compare-write is one atomic step.

  8. What does this program print? import java.util.concurrent.atomic.AtomicInteger; public class Q2 { public static void main(String[] args) { AtomicInteger value = new AtomicInteger(1); value.updateAndGet(n -> n * 10); value.accumulateAndGet(5, Math::max); System.out.println(value.get()); } }

    Answer

    10

    The update gives ten, and the maximum of ten and five is ten.

  9. What does addAndGet answer?

    Answer

    The new value

    The result is the value after the addition, and getAndAdd is the other order.

  10. Why is an atomic variable not a replacement for every lock?

    Answer

    It protects one value, and a lock protects an invariant over several

    The state of a class is often a relation between fields, and only a lock holds that whole relation.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev

Banner image