Skip to content
Tutorials Center
My learning

Topics

Lesson 131 of 201 ยท Concurrency

Atomic Variables

Learn Java atomic variables - AtomicInteger, AtomicLong, AtomicReference and AtomicBoolean, compareAndSet loops, LongAdder, and when atomics beat locks.

count++ looks like one step, but the CPU does three: read the value, add one, write it back. When two threads interleave those steps, one increment is silently lost. You already know one fix: wrap the update in synchronized or a Lock (Synchronization and Race Conditions, Locks and Conditions). That works, but every thread that wants the counter has to queue for the lock.

The classes in java.util.concurrent.atomic take a different route. They use a single hardware instruction, compare-and-swap (CAS), that updates a memory location only if it still holds the value you expect. No thread ever blocks waiting for another. In this lesson you'll use AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference, write your own CAS loops, meet LongAdder for heavily contended counters, and learn where atomics stop being enough.

The lost update problem

Here are four threads, each adding one million to two counters: a plain int field and an AtomicInteger. Run it a few times.

Java Plain int vs AtomicInteger

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The atomic counter is always exactly 4,000,000. The plain counter is almost always lower, and by a different amount each run. Even on a single CPU core, the scheduler can pause a thread between its read and its write; another thread then updates the field, and the paused thread overwrites that work with its stale value.

Making the field volatile doesn't help. volatile guarantees that every thread sees the latest write, but it doesn't make read-add-write indivisible. Atomics give you both: visibility and atomicity.

The AtomicInteger and AtomicLong API

AtomicInteger and AtomicLong share the same methods. Notice the naming pattern: getAndX returns the value before the change, xAndGet returns the value after it, just like postfix i++ and prefix ++i.

Java Atomic methods and their return values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Method Effect Returns
get() / set(v) read / write with volatile semantics value / nothing
incrementAndGet(), decrementAndGet() ยฑ1 new value
getAndIncrement(), getAndDecrement() ยฑ1 old value
addAndGet(d) / getAndAdd(d) add d new / old value
getAndSet(v) replace old value
updateAndGet(f) / getAndUpdate(f) apply f to the value new / old value
accumulateAndGet(x, f) / getAndAccumulate(x, f) apply f(current, x) new / old value
compareAndSet(expect, update) replace only if current equals expect true if it replaced

get() and set() behave exactly like reading and writing a volatile field, so an atomic is also a safe way to publish a value from one thread to another. There are weaker variants for experts (getPlain, setRelease, lazySet, weakCompareAndSetVolatile), but you rarely need them.

compareAndSet: the building block

Every atomic method is built on compareAndSet. The idea is optimistic: read the current value, compute the new one, then try to install it only if nobody changed the value in the meantime. If someone did, compareAndSet returns false and you start over with the fresh value. This is a CAS loop:

Java
int current, next;
do {
    current = counter.get();
    next = compute(current);
} while (!counter.compareAndSet(current, next));

updateAndGet is exactly this loop with your function as compute, which is why the function must be side-effect free: under contention it can run several times before one attempt wins.

The next example writes a CAS loop by hand for a rule no built-in method covers: a ticket counter that hands out numbers but never goes past a limit. Eight threads race for ten tickets.

Java A bounded counter with a CAS loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Eight buyers try three times each, so there are 24 attempts, yet exactly ten tickets with numbers 1 through 10 come out, never a duplicate and never an eleventh. Which buyer gets which ticket changes from run to run. The retry count is usually zero or small here because the threads barely overlap; in a busy server it climbs, and that's the cost of optimism: wasted attempts instead of waiting.

Two atomic calls in a row are not atomic together. if (issued.get() < LIMIT) issued.incrementAndGet(); is a check-then-act race: two threads can both pass the check before either increments, and you end up at 11. Fold the check into the CAS loop as above, or into updateAndGet(v -> v < LIMIT ? v + 1 : v).

AtomicBoolean: do something exactly once

AtomicBoolean is perfect for one-time actions such as shutting down a service, closing a resource, or printing a warning once. Only one caller can flip false to true:

Java
private final AtomicBoolean closed = new AtomicBoolean(false);

public void close() {
    if (closed.compareAndSet(false, true)) {
        releaseResources();          // runs once, no matter how many threads call close()
    }
}

AtomicReference: swapping whole objects

AtomicReference<V> holds a reference and updates it with CAS. Combined with an immutable object, it lets you change several related values at once without a lock: build a new object with the new values, then swap it in. Readers always see either the complete old object or the complete new one, never a half-updated mix.

Java AtomicReference with an immutable record

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Every run prints 100,000 requests, a max of 102 ms and an average of 51.00 ms, because no update is ever lost. If Stats had three separate AtomicLong fields instead, a reader could see a count that already includes a request whose sum hasn't been added yet.

compareAndSet on an AtomicReference compares references with ==, not equals. That's fine for the "read, build new, swap" pattern, because you pass back the exact object you read.

The ABA problem. CAS checks only that the value is the same as before, not that it never changed. If a value goes from A to B and back to A, a slow thread's CAS still succeeds. For counters that's harmless. For lock-free data structures that reuse nodes it can be a bug; AtomicStampedReference pairs the reference with a version number to detect it.

Atomic arrays and field updaters

AtomicIntegerArray, AtomicLongArray and AtomicReferenceArray give you atomic operations on each element, for example a histogram shared by many threads:

Java
var buckets = new AtomicIntegerArray(10);
buckets.incrementAndGet(score / 10);     // safe from any thread

An AtomicIntegerArray is different from an array of AtomicInteger objects: it's one compact array of ints, not ten separate objects. For the same memory reason, libraries with millions of objects sometimes use AtomicIntegerFieldUpdater or a VarHandle to do CAS on a plain volatile field instead of allocating an atomic object per instance. You'll mostly meet those inside JDK and library code.

LongAdder: counters under heavy contention

When many threads hammer the same AtomicLong, they all compete for one memory location, and CAS attempts fail and retry constantly. LongAdder spreads the work: each thread tends to add to its own internal cell, and sum() adds up the cells when you read. Writes scale almost perfectly; reads are a little more expensive and not an exact snapshot while writers are still running.

Java AtomicLong vs LongAdder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Both counters reach 8,000,000 and the accumulator reports 1,999,999. The timings depend on the machine. With one core, threads rarely collide and the two are similar; on a laptop or server with many cores running at once, LongAdder is often several times faster for pure writes. LongAccumulator generalizes the idea to any associative, side-effect-free function such as max, min or sum. DoubleAdder and DoubleAccumulator do the same for double.

Choose LongAdder for statistics that many threads update and few read: request counts, metrics, hit counters. Keep AtomicLong when you need the exact current value on every update, such as generating unique IDs with incrementAndGet(); LongAdder has no "add and return the new value".

Atomics or locks?

Atomics are not a replacement for every lock. Use this guide:

  • One variable, simple update (counter, flag, max, sequence number): an atomic is simpler and faster than a lock.
  • Many writers, rare reads of a total: LongAdder or LongAccumulator.
  • Several fields that must change together: put them in an immutable record inside an AtomicReference, or use a lock. Separate atomics can't keep an invariant between them.
  • Long or side-effecting work in the update (I/O, logging, calling other objects): use a lock. A CAS loop may repeat the work, and a lock lets you wait instead of spinning.
  • Very high contention on one value with a complex update: CAS retries can burn CPU. A lock (or a redesign that avoids sharing, like LongAdder does) is often better.

Many classes you'll use next are built from atomics internally: ConcurrentHashMap, ConcurrentLinkedQueue, the thread pools in Executors and Thread Pools and CompletableFuture.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. var n = new AtomicInteger(5); What does IO.println(n.getAndIncrement() + " " + n.get()); print?

    getAndIncrement returns the value before the change (5), and the following get sees the incremented value (6).
  2. 2. Why does a volatile int counter still lose updates when several threads run count++?

    volatile guarantees visibility and ordering, not atomicity. Two threads can still read the same old value and both write old + 1.
  3. 3. int v = a.get(); if (v < 10) a.set(v + 1); runs in many threads. What's wrong?

    Each method is atomic on its own, but the sequence is not. Use a compareAndSet loop or updateAndGet(x -> x < 10 ? x + 1 : x).
  4. 4. Why must the function passed to updateAndGet be free of side effects?

    updateAndGet reads, applies the function and tries compareAndSet. If another thread got there first, it repeats, calling the function again.
  5. 5. Which is the best fit for a hit counter that 50 threads increment constantly and a monitoring task reads once a minute?

    LongAdder spreads increments across cells to avoid contention and sums them on read. volatile long loses updates, and the other options serialize every write.

Summary

  • Compound updates like count++ race between threads; volatile fixes visibility but not atomicity.
  • AtomicInteger/AtomicLong offer incrementAndGet, getAndAdd, updateAndGet, accumulateAndGet and more; getAndX returns the old value, xAndGet the new one.
  • compareAndSet(expect, update) is the primitive behind all of them; a CAS loop retries until it wins, so update functions must be pure.
  • Several atomic calls in a row are not atomic together; fold checks into one CAS loop.
  • AtomicBoolean handles run-once flags; AtomicReference plus an immutable record updates several values as one.
  • LongAdder/LongAccumulator beat AtomicLong for heavily contended counters that are read rarely.
  • Use locks when several variables must stay consistent or the update does slow or side-effecting work.

Next: Executors and Thread Pools, where you'll stop creating threads by hand and let a pool run your tasks.