Skip to lesson

AtomicInteger and AtomicLong

A lock around count++ works, but it is a lot of machinery for one number. An atomic variable does the whole read, change and write of one value as a single step that no other thread can split, without any lock in your code.

incrementAndGet versus getAndIncrement

AtomicInteger is a class that holds one int which many threads can change safely, with methods such as incrementAndGet(). Each method does its read-change-write as one atomic step, without a lock. AtomicLong does the same for a long.

AtomicInteger (and AtomicLong for long values) holds one number that many threads can change safely. They live in java.util.concurrent.atomic. Each method does its whole read-change-write as one atomic step: other threads see it either not started or finished, never half done.

Example 1 · Which value comes back: new or old

AtomicReturnValuesDemo.javaJava
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicReturnValuesDemo {    public static void main(String[] args) {        AtomicInteger token = new AtomicInteger(10);
        System.out.println("incrementAndGet: " + token.incrementAndGet());  // 11, value now 11        System.out.println("getAndIncrement: " + token.getAndIncrement());  // 11, value now 12        System.out.println("value now:       " + token.get());        System.out.println("addAndGet(5):    " + token.addAndGet(5));        System.out.println("getAndAdd(5):    " + token.getAndAdd(5));       // 17, value now 22        System.out.println("decrementAndGet: " + token.decrementAndGet());        token.set(100);        System.out.println("after set(100):  " + token.get());    }}
Output
incrementAndGet: 11
getAndIncrement: 11
value now:       12
addAndGet(5):    17
getAndAdd(5):    17
decrementAndGet: 21
after set(100):  100

What this code does

  • ...AndGet methods change first and return the new value; getAnd... methods return the old value and then change it.
  • In a token machine, incrementAndGet() gives each customer the new token number; getAndIncrement() hands out the current number and moves on.
  • Each call is one atomic step, even though here only one thread uses the counter.

Example 2 · A lock-free counter for four UPI servers

AtomicCounterDemo.javaJava
import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicLong;
class PaymentStats {    private final AtomicInteger payments = new AtomicInteger();    private final AtomicLong totalPaise = new AtomicLong();
    void record(long amountPaise) {        payments.incrementAndGet();        totalPaise.addAndGet(amountPaise);    }
    int payments() {        return payments.get();    }
    long totalPaise() {        return totalPaise.get();    }}
public class AtomicCounterDemo {    public static void main(String[] args) throws InterruptedException {        PaymentStats stats = new PaymentStats();        Thread[] servers = new Thread[4];        for (int s = 0; s < 4; s++) {            servers[s] = new Thread(() -> {                for (int i = 0; i < 100_000; i++) {                    stats.record(499_900);           // Rs 4,999.00 in paise                }            }, "upi-server-" + (s + 1));            servers[s].start();        }        for (Thread t : servers) {            t.join();        }        System.out.println("Payments: " + stats.payments());        System.out.println("Total in paise: " + stats.totalPaise());        System.out.println("Fits in an int? " + (stats.totalPaise() <= Integer.MAX_VALUE));    }}
Output
Payments: 400000
Total in paise: 199960000000
Fits in an int? false

What this code does

  • Four threads record 100,000 payments each. No synchronized, no Lock, and the counts are exact on every run.
  • The total is 199,960,000,000 paise (about Rs 200 crore), far above the largest int, so it needs AtomicLong. Money is kept in whole paise to avoid double rounding errors.
  • The two counters are updated separately, so a reader in the middle could see one updated and not the other. That is fine for statistics, but not for values that must always agree.

The method names tell you which value comes back. incrementAndGet() adds one and returns the new value, like ++x. getAndIncrement() returns the old value and then adds one, like x++. The same pattern gives decrementAndGet, getAndDecrement, addAndGet(n) and getAndAdd(n). Plain get() and set(v) read and write the value with the same visibility as a volatile field. Use AtomicLong when the total can pass about 2.1 billion, the largest int.

Predict the output

New value or old value?

Read the code and pick what it prints.

Round 1 of 2

What does this program print?

import java.util.concurrent.atomic.AtomicInteger;
public class Round1 {
public static void main(String[] args) {
AtomicInteger orders = new AtomicInteger(5);
int a = orders.getAndIncrement();
int b = orders.incrementAndGet();
System.out.println(a + " " + b);
}
}

updateAndGet and accumulateAndGet with lambdas

updateAndGet(f) applies a function to the current value and stores the result atomically, for changes that are more than "add n". getAndUpdate(f) does the same but returns the old value.

accumulateAndGet(x, f) combines the current value with a new value x.

Example 3 · updateAndGet and accumulateAndGet: seats and top marks

UpdateAccumulateDemo.javaJava
import java.util.concurrent.atomic.AtomicInteger;
public class UpdateAccumulateDemo {    public static void main(String[] args) throws InterruptedException {        AtomicInteger seatsLeft = new AtomicInteger(5);        AtomicInteger highest = new AtomicInteger(0);        int[][] marksByThread = { {67, 88, 45}, {91, 72, 60}, {55, 79, 94}, {83, 40, 71} };
        Thread[] workers = new Thread[4];        for (int w = 0; w < 4; w++) {            int[] marks = marksByThread[w];            workers[w] = new Thread(() -> {                for (int m : marks) {                    highest.accumulateAndGet(m, Math::max);           // keep the larger one                    seatsLeft.updateAndGet(n -> n > 0 ? n - 1 : 0);   // never below zero                }            }, "evaluator-" + (w + 1));            workers[w].start();        }        for (Thread t : workers) {            t.join();        }        System.out.println("Highest marks: " + highest.get());        System.out.println("Merit seats left: " + seatsLeft.get());    }}
Output
Highest marks: 94
Merit seats left: 0

What this code does

  • accumulateAndGet(m, Math::max) replaces the stored value with the larger of the two, atomically. The highest of all 12 marks, 94, wins on every run.
  • Twelve students try to take 5 seats. The lambda stops at 0, so the count never goes negative.
  • Both lambdas only compute a value from their input. That matters because they may run more than once when threads collide.

For example, seats.updateAndGet(n -> n > 0 ? n - 1 : 0) never lets the seat count go below zero, and highest.accumulateAndGet(marks, Math::max) keeps the highest marks seen so far.

These methods may call your function more than once when threads compete (the next lesson shows why). So the lambda must only compute a result: no printing, no counters, no database calls inside it.

AtomicReference and AtomicBoolean

AtomicBoolean is a boolean with atomic operations. getAndSet(true) sets it to true and tells you what it was before, so exactly one thread sees false: a clean way to make sure something runs only once.

Example 4 · AtomicBoolean: send the results SMS only once

AtomicBooleanDemo.javaJava
import java.util.concurrent.atomic.AtomicBoolean;import java.util.concurrent.atomic.AtomicInteger;
class ResultNotifier {    private final AtomicBoolean sent = new AtomicBoolean(false);    private final AtomicInteger smsCount = new AtomicInteger();
    void notifyOnce() {        if (!sent.getAndSet(true)) {      // only the first caller sees false            smsCount.incrementAndGet();   // pretend to send the SMS        }    }
    int smsCount() {        return smsCount.get();    }}
public class AtomicBooleanDemo {    public static void main(String[] args) throws InterruptedException {        ResultNotifier notifier = new ResultNotifier();        Thread[] servers = new Thread[5];        for (int i = 0; i < 5; i++) {            servers[i] = new Thread(notifier::notifyOnce, "result-server-" + (i + 1));            servers[i].start();        }        for (Thread t : servers) {            t.join();        }        System.out.println("SMS sent: " + notifier.smsCount());    }}
Output
SMS sent: 1

What this code does

  • Five servers try to send the "results are out" SMS at once. getAndSet(true) returns false to exactly one of them.
  • A plain if (!sent) { sent = true; ... } would be a check-then-act race, and two servers could both send it.
  • Which server wins changes from run to run, but the count is always 1.

Example 5 · AtomicReference: swap a whole immutable score

AtomicReferenceDemo.javaJava
import java.util.concurrent.atomic.AtomicReference;
record Score(int runs, int wickets) {    Score addBall(int r, boolean out) {        return new Score(runs + r, out ? wickets + 1 : wickets);    }}
public class AtomicReferenceDemo {    public static void main(String[] args) throws InterruptedException {        AtomicReference<Score> live = new AtomicReference<>(new Score(0, 0));
        Runnable scorer = () -> {            for (int ball = 1; ball <= 600; ball++) {                boolean out = ball % 100 == 0;                live.updateAndGet(s -> s.addBall(1, out));            }        };        Thread a = new Thread(scorer, "scorer-1");        Thread b = new Thread(scorer, "scorer-2");        a.start();        b.start();        a.join();        b.join();
        Score s = live.get();        System.out.println("Final score: " + s.runs() + "/" + s.wickets());    }}
Output
Final score: 1200/12

What this code does

  • Score is a record, so it never changes. Each update builds a new Score and swaps the reference atomically.
  • Runs and wickets live in one object, so a reader always sees a matching pair, never runs from one ball and wickets from another.
  • Two threads add 600 balls each, with a wicket every 100 balls: always 1200 runs and 12 wickets.

AtomicReference<V> holds a reference to an object. It is most useful with an immutable object, such as a record: to change it, you build a new object and swap the reference in one atomic step with set or updateAndGet. Readers always see either the old object or the new one, never a mix. This lets you keep two related values consistent without a lock, by putting them in one immutable object.

volatile versus atomic variables

volatile guarantees visibility: a write is seen by later reads in other threads. It does not make count++ safe, because count++ is still three separate steps (read, add, write) and two threads can interleave them.

Example 6 · volatile int versus AtomicInteger under four threads

VolatileVersusAtomicDemo.javaJava
import java.util.concurrent.atomic.AtomicInteger;
public class VolatileVersusAtomicDemo {    static volatile int volatileCount = 0;    static final AtomicInteger atomicCount = new AtomicInteger();
    public static void main(String[] args) throws InterruptedException {        Thread[] threads = new Thread[4];        for (int t = 0; t < 4; t++) {            threads[t] = new Thread(() -> {                for (int i = 0; i < 100_000; i++) {                    volatileCount++;                  // read, add, write: can interleave                    atomicCount.incrementAndGet();    // one atomic step                }            }, "worker-" + (t + 1));            threads[t].start();        }        for (Thread t : threads) {            t.join();        }        System.out.println("Expected:       400000");        System.out.println("volatile int:   " + volatileCount);        System.out.println("AtomicInteger:  " + atomicCount.get());    }}
Sample output
Expected:       400000
volatile int:   231889
AtomicInteger:  400000

What this code does

  • volatile makes every write visible, but two threads can still read the same old value and both write old + 1, so updates are lost. The number changes from run to run.
  • incrementAndGet() reads, adds and writes as one atomic step, so the atomic count is exactly 400000 on every run.
  • On a machine with a single core the volatile count may come close to 400000, but it is never guaranteed.

The choice depends on what the threads do with the value:

  • volatile boolean running: one writer, many readers. Good.
  • volatile int count; count++ from many threads: loses updates.
  • AtomicInteger count; count.incrementAndGet(): correct and lock-free.
  • Several values that must change together: a lock, or one immutable object in an AtomicReference.

An atomic variable gives visibility and atomic read-modify-write operations. So volatile is right for a flag that one thread sets and others read; an atomic is right for a value that several threads update based on its current value.

Next step

Check your understanding

12 quick questions