JAVA-240 · Lesson 4 of 12 · 22 min

Locks and atomic variables

▶ Video coming soon A video version of this lesson is on the way.

Monday, January 31, 2028. Hamza has fixed Kofi's minus-one tube with a synchronized method, and it works. Ingrid wants him to know the rest of the toolbox before he builds OrderDesk. synchronized is simple, but it cannot try for a lock and give up, it cannot wait with a time limit, and it treats readers and writers alike. The package java.util.concurrent.locks has explicit locks that can do all of those things, and java.util.concurrent.atomic has classes that make single variables thread-safe without any lock at all.

ReentrantLock

A ReentrantLock does the same basic job as synchronized: one thread at a time holds it, and the holder can take it again without waiting for itself. The difference is that you call lock and unlock yourself. That gives more control and one new danger: if an exception is thrown between lock and unlock, the lock is never released, and every other thread that needs it waits forever. The standard pattern therefore puts unlock in a finally block, with lock called just before the try.

Java Example · Main.java
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    static final ReentrantLock lock = new ReentrantLock();
    static int pickedLines = 0;

    static void pickLine() {
        lock.lock();
        try {
            pickedLines++;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread[] pickers = new Thread[4];
        for (int i = 0; i < 4; i++) {
            pickers[i] = new Thread(() -> {
                for (int n = 0; n < 50_000; n++) pickLine();
            });
            pickers[i].start();
        }
        for (Thread t : pickers) t.join();
        System.out.println("lines picked: " + pickedLines);
        System.out.println("lock held now? " + lock.isLocked());
    }
}
Output
lines picked: 200000
lock held now? false

What this code does

Four threads each record 50,000 picked lines through a method that takes a ReentrantLock, increments and releases the lock in a finally block. The total is exactly 200,000 every time, and the lock is free at the end. The finally block guarantees the unlock even if the code inside the try throws.

Ingrid's rule is short: if synchronized does what you need, use synchronized, because the compiler takes care of releasing it. Reach for ReentrantLock when you need one of its extra abilities: tryLock, a timed or interruptible wait, fairness, or several separate waiting conditions.

Trying for a lock

tryLock asks for the lock and returns at once with true if it got it and false if another thread holds it. A version with a time limit waits up to that long before giving up. This lets a thread do something sensible instead of waiting forever: report that the stock list is busy, retry later, or, as lesson 9 shows, avoid a deadlock.

Java Example · Main.java
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock stockList = new ReentrantLock();
        String[] result = new String[2];

        stockList.lock();
        try {
            Thread impatient = new Thread(() -> {
                try {
                    if (stockList.tryLock(100, TimeUnit.MILLISECONDS)) {
                        try { result[0] = "updated the stock list"; } finally { stockList.unlock(); }
                    } else {
                        result[0] = "stock list busy, will try again later";
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
            impatient.start();
            impatient.join();
        } finally {
            stockList.unlock();
        }

        Thread patient = new Thread(() -> {
            if (stockList.tryLock()) {
                try { result[1] = "updated the stock list"; } finally { stockList.unlock(); }
            } else {
                result[1] = "stock list busy";
            }
        });
        patient.start();
        patient.join();

        System.out.println("while main held the lock: " + result[0]);
        System.out.println("after main released it:   " + result[1]);
    }
}
Output
while main held the lock: stock list busy, will try again later
after main released it:   updated the stock list

What this code does

Main holds the stock list lock while a thread tries for it with a 100-millisecond limit; the try fails and the thread reports that the list is busy. After main releases the lock, a second thread's tryLock succeeds at once. In both threads, unlock is called only when tryLock returned true, because unlocking a lock you do not hold throws IllegalMonitorStateException.

A ReentrantLock can also be created as fair, with new ReentrantLock(true). A fair lock hands itself to the thread that has waited longest. Unfair locks, the default, let a newly arriving thread jump the queue, which is usually faster overall but can, in rare cases, leave a thread waiting much longer than others. Lesson 9 returns to this as starvation.

Read-write locks

Many shared structures are read far more often than they are written. The shop's price list is a good example: every order looks up prices, but Kofi updates the list from the supplier once a night. A single lock forces readers to take turns even though readers cannot harm each other. A ReadWriteLock has two locks in one: any number of threads may hold the read lock at the same time, but the write lock is exclusive and waits until no one is reading.

Java Example · Main.java
import java.util.*;
import java.util.concurrent.locks.*;

public class Main {
    static class PriceList {
        private final Map<String, Integer> cents = new TreeMap<>();
        private final ReadWriteLock rw = new ReentrantReadWriteLock();

        int price(String code) {
            rw.readLock().lock();
            try {
                return cents.getOrDefault(code, -1);
            } finally {
                rw.readLock().unlock();
            }
        }

        void update(String code, int newCents) {
            rw.writeLock().lock();
            try {
                cents.put(code, newCents);
            } finally {
                rw.writeLock().unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        PriceList list = new PriceList();
        list.update("TUBE-700x25", 899);
        list.update("PAD-ROAD", 1499);

        long[] lookups = new long[4];
        Thread[] readers = new Thread[4];
        for (int i = 0; i < 4; i++) {
            int r = i;
            readers[i] = new Thread(() -> {
                for (int n = 0; n < 10_000; n++) if (list.price("PAD-ROAD") > 0) lookups[r]++;
            });
            readers[i].start();
        }
        Thread writer = new Thread(() -> list.update("TUBE-700x25", 949));
        writer.start();

        for (Thread t : readers) t.join();
        writer.join();

        System.out.println("lookups answered: " + Arrays.stream(lookups).sum());
        System.out.println("tube price now: " + list.price("TUBE-700x25"));
    }
}
Output
lookups answered: 40000
tube price now: 949

What this code does

Four reader threads look up a price 10,000 times each under the read lock, which they can all hold together, while a writer changes another price under the exclusive write lock. Every lookup gets an answer and the final price is the writer's new value. The readers never wait for each other, only for the brief moment the writer holds its lock.

Read-write locks pay off only when reads really dominate and each read holds the lock for a while. For a tiny map read in nanoseconds, the bookkeeping can cost more than it saves, and a ConcurrentHashMap from lesson 5 is usually the better choice. As always with performance, measure rather than assume.

Atomic variables

The package java.util.concurrent.atomic provides classes such as AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference. Each holds a single value and offers methods that read and change it as one atomic step, with no lock. incrementAndGet replaces count++; addAndGet adds any amount; getAndSet swaps in a new value and returns the old one. Their reads and writes also have the same visibility guarantees as volatile.

Java Example · Main.java
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    static final AtomicInteger sold = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
        Thread[] clerks = new Thread[4];
        for (int i = 0; i < 4; i++) {
            clerks[i] = new Thread(() -> {
                for (int n = 0; n < 100_000; n++) sold.incrementAndGet();
            });
            clerks[i].start();
        }
        for (Thread t : clerks) t.join();
        System.out.println("expected 400000, got " + sold.get());
    }
}
Output
expected 400000, got 400000

What this code does

This is lesson 3's losing counter rewritten with an AtomicInteger. incrementAndGet reads, adds and writes as one indivisible operation, so no increment is ever lost. There is no lock and no synchronized keyword, yet the total is exactly 400,000 on every run.

Compare-and-set

Under the hood, the atomic classes are built on a single processor instruction, compare-and-set, often written CAS. compareAndSet(expected, newValue) changes the variable to newValue only if it still holds expected, and returns whether it did. If another thread got there first, nothing changes and the method returns false, and the caller tries again with the fresh value. Code that works this way, retrying instead of waiting for a lock, is called lock-free.

A flowchart of a compare-and-set loop. Read the current value. Compute the new value from it. Then a decision: does the variable still hold the value read? If yes, write the new value and finish. If no, go back to reading the current value.
A compare-and-set retry loop

The updateAndGet method wraps that retry loop for you: you pass a function from the old value to the new one, and it keeps applying the function until its compare-and-set succeeds. The function may therefore run more than once, so it must be quick and have no side effects. Here is a stock reservation that can never drive the count below zero, without any lock:

Java Example · Main.java
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        AtomicInteger tubes = new AtomicInteger(5);
        AtomicInteger confirmed = new AtomicInteger();

        Thread[] customers = new Thread[12];
        for (int i = 0; i < 12; i++) {
            customers[i] = new Thread(() -> {
                while (true) {
                    int now = tubes.get();
                    if (now == 0) return;
                    if (tubes.compareAndSet(now, now - 1)) {
                        confirmed.incrementAndGet();
                        return;
                    }
                }
            });
            customers[i].start();
        }
        for (Thread t : customers) t.join();

        System.out.println("confirmations: " + confirmed.get());
        System.out.println("tubes left: " + tubes.get());
    }
}
Output
confirmations: 5
tubes left: 0

What this code does

Twelve customers try to reserve one of five tubes, each by reading the count and trying to compare-and-set it one lower. If another customer changed the count in between, the compare-and-set fails and the customer reads again. Exactly five reservations succeed and the count stops at 0, never below.

LongAdder for busy counters

An AtomicLong that many threads hammer at once becomes a bottleneck: every compare-and-set fights over the same memory location, and failed attempts retry. LongAdder solves this for counters that are updated often and read rarely, such as the number of web requests served. It spreads the count over several cells, so threads mostly update different cells, and adds them up only when you call sum. The price is that sum is not an atomic snapshot if updates are still happening; read it when the counting is done or when an approximate figure is good enough.

Java Example · Main.java
import java.util.concurrent.atomic.LongAdder;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        LongAdder pageViews = new LongAdder();
        Thread[] servers = new Thread[8];
        for (int i = 0; i < 8; i++) {
            servers[i] = new Thread(() -> {
                for (int n = 0; n < 250_000; n++) pageViews.increment();
            });
            servers[i].start();
        }
        for (Thread t : servers) t.join();
        System.out.println("page views: " + pageViews.sum());
    }
}
Output
page views: 2000000

What this code does

Eight threads each count 250,000 page views on one LongAdder, and main reads the sum after joining them all. Because the threads have finished, the sum is exact: 2,000,000 every time. While threads are still counting, sum would give a figure that might already be out of date.

Choosing a tool for shared state
ToolWhat it protectsCan it wait with a time limit?Best for
synchronizedA block or method, using an object's monitorNoMost ordinary critical sections
ReentrantLockCode between lock and unlockYes, tryLock(time)When you need tryLock, timeouts, fairness or conditions
ReentrantReadWriteLockData read by many, written by fewYesRead-heavy structures with slow reads
AtomicInteger and friendsOne variableNever waits; retriesCounters, flags, single references
LongAdderOne counterNever waitsVery busy counters read rarely

Conditions: waiting for something to become true

Sometimes a thread must wait not for a lock but for a condition: wait until the parts bin has something in it, wait until a repair slot frees up. Every ReentrantLock can create Condition objects for this. A thread holding the lock calls await on a condition, which releases the lock and suspends the thread until another thread calls signal or signalAll on the same condition. The awakened thread takes the lock back before await returns. Because a thread can wake for other reasons, always wait in a loop that rechecks the condition.

The older form of the same idea uses wait and notifyAll on an object's monitor inside synchronized. Both work, but in new code you will rarely write either yourself: the blocking queues of lesson 10 and the latches and semaphores of lessons 8 and 11 package the common patterns, tested and ready.

Which tool, and when

Hamza asks the obvious question: if atomics are lock-free and fast, why not use them everywhere? Ingrid's answer is that an atomic variable protects one variable, and most real invariants involve several. The ledger from lesson 3 had to keep two drawers in step; two separate AtomicIntegers could each be updated atomically and still be seen half-transferred. Whenever a rule links more than one value, you need a lock around all of them, or a design that puts them in one immutable object swapped in with a single AtomicReference.

Try it yourself

Reservations that never go negative

Use AtomicInteger.updateAndGet to reserve tubes: each of 10 threads asks for 2 tubes from a stock of 7, and a request is granted only if at least 2 are left. Count the granted requests with a second AtomicInteger.

The program should print granted: 3 and left: 1.

import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        AtomicInteger stock = new AtomicInteger(7);
        AtomicInteger granted = new AtomicInteger();
        Thread[] ts = new Thread[10];
        for (int i = 0; i < 10; i++) {
            ts[i] = new Thread(() -> {
                // reserve 2 tubes if at least 2 are left, and count the grant
            });
            ts[i].start();
        }
        for (Thread t : ts) t.join();
        System.out.println("granted: " + granted.get());
        System.out.println("left: " + stock.get());
    }
}

Try it yourself

A lock-protected list

Three threads each add the numbers 0 to 999 to one shared ArrayList. Protect the add with a ReentrantLock, using the lock-try-finally-unlock pattern, so the list always ends with 3,000 items.

The program should print items: 3000 and sum: 1498500.

import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    static final List<Integer> picks = new ArrayList<>();
    static final ReentrantLock lock = new ReentrantLock();

    static void add(int n) {
        // add n under the lock
    }

    public static void main(String[] args) throws InterruptedException {
        Thread[] ts = new Thread[3];
        for (int i = 0; i < 3; i++) {
            ts[i] = new Thread(() -> { for (int n = 0; n < 1000; n++) add(n); });
            ts[i].start();
        }
        for (Thread t : ts) t.join();
        System.out.println("items: " + picks.size());
        System.out.println("sum: " + picks.stream().mapToLong(Integer::longValue).sum());
    }
}

Common mistakes

  • MistakeCalling lock() inside the try block, or forgetting unlock.

    InsteadCall lock() just before try and unlock() in finally, every time.

  • MistakeCalling unlock after a tryLock that returned false.

    InsteadUnlock only when tryLock returned true; otherwise you do not hold the lock.

  • MistakeUsing two AtomicIntegers for values that must change together.

    InsteadProtect related values with one lock, or keep them in one immutable object behind an AtomicReference.

  • MistakePutting side effects inside the function passed to updateAndGet.

    InsteadKeep it pure and quick: it may run several times before the compare-and-set succeeds.

  • MistakeReading LongAdder.sum as an exact snapshot while updates continue.

    InsteadRead it after the updates finish, or accept that it may be slightly out of date.

Summary and key terms

  • ReentrantLock is an explicit, reentrant lock: call lock just before try and unlock in finally.
  • It adds tryLock, timed and interruptible waits, optional fairness and Condition objects.
  • A ReentrantReadWriteLock lets many readers share the read lock while the write lock is exclusive, which helps read-heavy data with slow reads.
  • Atomic classes such as AtomicInteger, AtomicLong and AtomicReference change one variable atomically without a lock, with volatile-style visibility.
  • They are built on compare-and-set, which changes a value only if it still holds the expected value; code that retries on failure is lock-free. updateAndGet and getAndUpdate wrap the retry loop and may call your function more than once.
  • LongAdder spreads a busy counter over cells and adds them on sum.
  • An atomic variable protects one value, so rules linking several values still need a lock or an immutable object swapped atomically.
ReentrantLock
An explicit lock that the holding thread can take again, released with unlock.
tryLock
A method that takes a lock only if it is free, or within a time limit.
Fair lock
A lock that is granted to the longest-waiting thread first.
ReadWriteLock
A pair of locks: a shared read lock and an exclusive write lock.
Atomic variable
An object such as AtomicInteger whose single value can be read and changed atomically.
Compare-and-set
An operation that changes a value only if it still equals an expected value.
Lock-free
Code that makes progress by retrying atomic operations instead of waiting for locks.
LongAdder
A counter that spreads updates over several cells to reduce contention.
Contention
Many threads competing for the same lock or memory location at the same time.
Condition
An object from a lock that threads can await until another thread signals it.
IllegalMonitorStateException
The exception thrown when a thread unlocks a lock it does not hold.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why must unlock go in a finally block?

    Show answer

    So the lock is released even if the code inside the try throws an exception.

  2. What does tryLock() return if another thread holds the lock?

    Show answer

    false, at once, without waiting.

  3. Can two threads hold a ReentrantReadWriteLock's read lock at the same time?

    Show answer

    Yes; only the write lock is exclusive.

  4. What does compareAndSet(4, 3) do if the value is now 5?

    Show answer

    Nothing; it returns false and the value stays 5.

  5. Why can't two AtomicIntegers keep a cash transfer consistent?

    Show answer

    Each is atomic on its own, but another thread can see the moment between the two updates.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz