Skip to lesson

Test concurrent code honestly

A concurrency test that passes once tells you almost nothing, because the bug may need a timing that did not happen. An honest test makes threads really overlap, repeats many times, checks rules rather than order, and fails with a clear message instead of hanging.

Why one passing run proves nothing

An interleaving is one particular order in which the steps of different threads mix. A concurrency bug shows only in some interleavings, so one passing run proves very little.

A concurrency bug needs a particular interleaving: the order in which the steps of different threads happen to mix. One run tries one interleaving out of millions. If it passes, it only proves that this one order worked, on this machine, this time.

Example 1 · One small run passes, bigger runs fail

OnePassDemo.javaJava
class LikeCounter {    private volatile int likes = 0;   // volatile: visible, but likes++ is still not atomic
    void like() { likes++; }          // not thread-safe: read, add, write    int likes() { return likes; }}
public class OnePassDemo {    // one "test": two threads add likes, then we compare with the expected total    static boolean testOnce(int perThread) throws InterruptedException {        LikeCounter c = new LikeCounter();        Thread a = new Thread(() -> { for (int i = 0; i < perThread; i++) c.like(); });        Thread b = new Thread(() -> { for (int i = 0; i < perThread; i++) c.like(); });        a.start();        b.start();        a.join();        b.join();        return c.likes() == 2 * perThread;    }
    public static void main(String[] args) throws InterruptedException {        System.out.println("One small run: " + (testOnce(100) ? "PASS" : "FAIL"));
        int failures = 0;        for (int run = 0; run < 100; run++) {            if (!testOnce(10_000)) failures++;        }        System.out.println("100 bigger runs: " + failures + " failed");    }}
Sample output
One small run: PASS
100 bigger runs: 16 failed

What this code does

  • The small run passes: with only 100 likes per thread, the threads hardly overlap. A developer who runs it once would call the code correct.
  • The bigger runs fail sometimes, and the count changes on every run (here 16 of 100). likes is volatile only so the JIT compiler cannot turn the loop into one big addition, which would hide the race even better.

Small tests are the worst. With 100 increments per thread, the first thread often finishes before the second even starts, so there is no race to find. The same code fails regularly with 10,000 increments, and it may fail even more often on a server with more cores.

Running many times with a start latch

A stress test runs the same check many times, with several threads and enough work per thread to make them overlap. Each round uses a fresh object, so damage from one round cannot hide in the next.

Example 2 · A stress harness with a start gate

StressHarnessDemo.javaJava
import java.util.concurrent.CountDownLatch;import java.util.concurrent.atomic.AtomicInteger;
interface Counter {    void add();    int get();}
class PlainCounter implements Counter {    private volatile int n;          // volatile does not make n++ atomic    public void add() { n++; }    public int get() { return n; }}
class AtomicCounter implements Counter {    private final AtomicInteger n = new AtomicInteger();    public void add() { n.incrementAndGet(); }    public int get() { return n.get(); }}
public class StressHarnessDemo {    static final int THREADS = 4, PER_THREAD = 10_000, ROUNDS = 50;
    static boolean round(Counter counter) throws InterruptedException {        CountDownLatch start = new CountDownLatch(1);        CountDownLatch done = new CountDownLatch(THREADS);        for (int t = 0; t < THREADS; t++) {            new Thread(() -> {                try {                    start.await();                    for (int i = 0; i < PER_THREAD; i++) counter.add();                } catch (InterruptedException e) {                    Thread.currentThread().interrupt();                } finally {                    done.countDown();                }            }, "stress-" + t).start();        }        start.countDown();                            // open the gate        done.await();                                 // wait for all of them        return counter.get() == THREADS * PER_THREAD;    }
    static void stress(String name, boolean atomic) throws InterruptedException {        int passed = 0;        for (int r = 0; r < ROUNDS; r++) {            if (round(atomic ? new AtomicCounter() : new PlainCounter())) passed++;        }        System.out.println(name + ": " + passed + " of " + ROUNDS + " rounds passed");    }
    public static void main(String[] args) throws InterruptedException {        stress("AtomicCounter", true);        stress("PlainCounter ", false);    }}
Sample output
AtomicCounter: 50 of 50 rounds passed
PlainCounter : 35 of 50 rounds passed

What this code does

  • Each round creates fresh threads that wait at start.await(), then all begin together when main calls start.countDown(). done.await() returns once all four have finished, and only then is the result checked.
  • The same harness gives AtomicCounter 50 passes out of 50 and catches PlainCounter in many rounds. The number of failed rounds changes from run to run.

A start latch, a CountDownLatch(1), makes the overlap real. Every thread is created first and waits at the gate; then main opens it with countDown() and they all start together. A second latch, counted down by each thread when it finishes, tells main when to check the result.

Checking invariants instead of exact output order

The order in which threads run changes on every run, so a test must never expect a fixed order, such as "thread 1 books seat 1".

Example 3 · Check the rules, not the order

InvariantTestDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.HashSet;import java.util.List;import java.util.Set;import java.util.concurrent.CountDownLatch;
class SeatCounter {    private final int capacity;    private int nextSeat = 1;
    SeatCounter(int capacity) { this.capacity = capacity; }
    // returns a seat number, or -1 when the show is full    synchronized int book() {        if (nextSeat > capacity) return -1;        return nextSeat++;    }}
public class InvariantTestDemo {    static void check(String rule, boolean ok) {        System.out.println((ok ? "PASS " : "FAIL ") + rule);    }
    public static void main(String[] args) throws InterruptedException {        int capacity = 300, threads = 8, requestsEach = 50;     // 400 requests for 300 seats        SeatCounter counter = new SeatCounter(capacity);        List<Integer> seats = Collections.synchronizedList(new ArrayList<>());        List<Integer> refused = Collections.synchronizedList(new ArrayList<>());
        CountDownLatch start = new CountDownLatch(1);        CountDownLatch done = new CountDownLatch(threads);        for (int t = 0; t < threads; t++) {            new Thread(() -> {                try {                    start.await();                    for (int i = 0; i < requestsEach; i++) {                        int seat = counter.book();                        if (seat == -1) refused.add(seat); else seats.add(seat);                    }                } catch (InterruptedException e) {                    Thread.currentThread().interrupt();                } finally {                    done.countDown();                }            }).start();        }        start.countDown();        done.await();
        // which thread got which seat changes every run, so we never check the order        Set<Integer> unique = new HashSet<>(seats);        check("every request got a seat or a refusal", seats.size() + refused.size() == threads * requestsEach);        check("no seat was sold twice", unique.size() == seats.size());        check("the show is exactly full", seats.size() == capacity);        check("every seat number is between 1 and 300",                Collections.min(seats) == 1 && Collections.max(seats) == capacity);    }}
Output
PASS every request got a seat or a refusal
PASS no seat was sold twice
PASS the show is exactly full
PASS every seat number is between 1 and 300

What this code does

  • 400 requests race for 300 seats. Which thread gets which seat differs on every run, so the test checks rules instead: every request answered, no duplicates (the HashSet drops them), exactly 300 sold, all numbers in range.
  • These checks give the same result on every correct run, so the output can be compared exactly. If book lost its synchronized, the duplicate check would start failing.

Check the rules that must hold in any order: no seat sold twice, the show exactly full, every request answered.

Good checks count and compare: the number of successes, the size of a Set of results (duplicates disappear in a set), totals and sums. They pass on every correct run and fail on every run in which a rule broke.

Timeouts so a deadlocked test fails instead of hanging

A test that deadlocks does not fail; it hangs, and the whole build waits forever. Every concurrency test needs a time limit: run the test body on another thread, wait with Future.get(timeout, unit), and report a failure when the time runs out.

Example 4 · A deadlocked test fails instead of hanging

TimeoutTestDemo.javaJava
import java.util.concurrent.Callable;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;
class Account {    final int id;    int balance = 1000;    Account(int id) { this.id = id; }}
public class TimeoutTestDemo {    // runs a test on a daemon thread and gives up after 'ms' milliseconds    static void runTest(String name, Callable<Boolean> test, long ms) {        ExecutorService runner = Executors.newSingleThreadExecutor(r -> {            Thread t = new Thread(r, "test-" + name);            t.setDaemon(true);            return t;        });        Future<Boolean> result = runner.submit(test);        try {            System.out.println((result.get(ms, TimeUnit.MILLISECONDS) ? "PASS " : "FAIL ") + name);        } catch (TimeoutException e) {            System.out.println("FAIL " + name + ": no answer after " + ms + " ms (deadlock?)");        } catch (InterruptedException | ExecutionException e) {            System.out.println("FAIL " + name + ": " + e.getCause());        } finally {            runner.shutdownNow();        }    }
    static boolean twoTransfers(boolean ordered) throws InterruptedException {        Account a = new Account(1), b = new Account(2);        CountDownLatch bothHoldOne = new CountDownLatch(2);    // forces the bad timing        Runnable aToB = () -> move(a, b, ordered, bothHoldOne);        Runnable bToA = () -> move(b, a, ordered, bothHoldOne);        Thread t1 = new Thread(aToB), t2 = new Thread(bToA);        t1.setDaemon(true);        t2.setDaemon(true);        t1.start();        t2.start();        t1.join();                              // a plain join: it would wait forever        t2.join();        return a.balance + b.balance == 2000;    }
    static void move(Account from, Account to, boolean ordered, CountDownLatch latch) {        Account first = ordered && from.id > to.id ? to : from;        Account second = first == from ? to : from;        synchronized (first) {            if (!ordered) {                latch.countDown();                try { latch.await(); } catch (InterruptedException e) { return; }            }            synchronized (second) {                from.balance -= 10;                to.balance += 10;            }        }    }
    public static void main(String[] args) {        runTest("transfers-in-id-order", () -> twoTransfers(true), 500);        runTest("transfers-in-opposite-order", () -> twoTransfers(false), 500);        System.out.println("Test run finished");    }}
Output
PASS transfers-in-id-order
FAIL transfers-in-opposite-order: no answer after 500 ms (deadlock?)
Test run finished

What this code does

  • runTest runs each test on a daemon thread and waits at most 500 ms with Future.get. The ordered transfers pass; the opposite-order transfers deadlock (forced by the latch), and the test reports a failure instead of hanging.
  • shutdownNow() interrupts the runner, and because the stuck threads are daemon threads, the JVM can still exit, so Test run finished is printed.

Make the test threads daemon threads, so a stuck test cannot keep the JVM alive.

Test frameworks have this built in: JUnit 5 has the @Timeout annotation and assertTimeoutPreemptively. For low-level code such as a custom lock-free class, the OpenJDK project's jcstress tool runs tiny tests millions of times to explore many interleavings.

A stress test that passes a thousand rounds still does not prove the code correct; it only failed to find a bug. Correctness comes from design (one lock per rule, immutable data, ready-made thread-safe classes); tests catch the mistakes.

Next step

Check your understanding

12 quick questions