How-To Guide

How to Test Concurrent Code Reliably

Test concurrent code without flakes: control the schedule, use barriers and latches, assert invariants under contention, and run the race detector.

On this page

  1. Introduction
  2. Control the interleaving with barriers
  3. Assert an invariant under contention
  4. Repeat and stress to expose a race
  5. Run the race detector
  6. Test the synchronization itself and its absence
  7. Common pitfalls
  8. Conclusion

Introduction

Concurrent code is hard to test because the bug depends on the interleaving, and the interleaving depends on timing. A test that sleeps and hopes two operations overlap is flaky: under load the overlap does not happen and the test passes without exercising the race. A reliable test controls the schedule, forcing the operations to a known point together, and asserts an invariant that must hold no matter the interleaving.

This tutorial covers controlling the interleaving with barriers, asserting an invariant under contention, repeating to expose a race, and enabling the race detector. The examples use barriers and a race detector, and the approach applies to shared-memory concurrency in any language.

Control the interleaving with barriers

A barrier or a latch makes operations wait until the others are ready, so they arrive at the contended point together rather than relying on a sleep. A test that starts two writers, has each wait on a barrier, then releases them, forces them to contend at a known moment. The interleaving becomes deterministic rather than timing-dependent, so the race is exercised on every run.

Use the coordination primitive the language offers: a WaitGroup or a barrier, a latch, a channel, or a promise all serve. The point is that the test, not the machine’s timing, decides when the operations meet. A test built on barriers is reproducible; a test built on sleeps is a coin flip.

function barrier(n) {
  let count = 0; const waiters = [];
  return () => new Promise((resolve) => {
    count++;
    if (count === n) { waiters.forEach((r) => r()); resolve(); }
    else waiters.push(resolve);
  });
}

it('loses no update under contention', async () => {
  const sync = barrier(2);
  const increment = async () => { await sync(); await counter.increment(); };
  await Promise.all([increment(), increment()]);   // they meet at the barrier
  expect(counter.value()).toBe(2);                 // no lost update
});

Assert an invariant under contention

The assertion should be a postcondition that must hold regardless of the interleaving, such as a total that equals the sum of the increments, a set that contains every inserted key, or a queue with no lost item. Asserting only that no exception was thrown is weak: a race often produces a wrong result without an error, so the test must check the result the race would corrupt.

Choose the invariant that the race would break. For a counter, it is the total; for a map, it is the contents; for a queue, it is the set of processed items and that none was processed twice. The invariant is what the synchronization protects, so asserting it is asserting that the protection works.

func TestConcurrentAppend(t *testing.T) {
    var mu sync.Mutex
    var items []int
    var wg sync.WaitGroup
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func(n int) { defer wg.Done(); mu.Lock(); items = append(items, n); mu.Unlock() }(i)
    }
    wg.Wait()
    if len(items) != 100 {          // the invariant: no append lost
        t.Fatalf("lost appends: got %d want 100", len(items))
    }
}

Repeat and stress to expose a race

A race may not appear in a single run, so run the contended case many times, or with many more workers than cores, to make the interleaving likely. A test that runs the case once and passes is not evidence; a test that runs it a thousand times and passes is stronger, and one that fails intermittently names the race. The repetition is what turns a rare interleaving into a detectable one.

Stress the boundaries: many workers, a short critical section so the contention window is narrow, and a loop so the operations contend repeatedly. Reduce the coordination so the interleavings are more varied. The goal is to make the race probable enough to catch, without making the test so slow it is skipped.

# run the contended case many times to expose an intermittent race
go test -run TestConcurrentAppend -count=1000 ./...
# a single pass is weak evidence; a failure names the race and its interleaving

Run the race detector

A race detector flags an unsynchronized access to shared memory even when the result of a given run happens to look correct, which is exactly the race a result assertion can miss. Run the test suite under the detector, and treat every report as a real race to fix, because the runtime instrumented the memory accesses and saw two unsynchronized ones. The detector is the closest thing to a proof that no data race exists on the exercised paths.

Enable it in a dedicated CI job, because the detector slows execution and should not blanket the normal suite. Combine it with the stress run, so the detector sees the contended interleavings. A detector report with the two stacks points at the exact unsynchronized accesses, which is far more useful than a random failure of a result assertion.

# race detector on the contended test: a report names the two accesses
go test -race -run TestConcurrent -count=50 ./...
# any WARNING: DATA RACE is a real bug to fix, even if the result looked correct

Test the synchronization itself and its absence

Write a test that removes the synchronization and assert the test fails, which proves the test is capable of detecting the race. A test that passes with and without the lock is not testing the lock. This negative check is what makes the concurrent test trustworthy: it shows the invariant breaks when the protection is removed.

Test the lock released on failure, the semaphore permit released on error, and the barrier not deadlocking when one operation fails, because the failure paths of a synchronization primitive are where a deadlock hides. A barrier that waits forever when one participant throws is a test hang, not a failure, so bound the wait and fail if the barrier does not reach its count.

Common pitfalls

Sleeping and hoping for an overlap so the test flakes, asserting only that no error was thrown, running the contended case once so a rare race is missed, no race detector so an unsynchronized access passes, and a barrier with no timeout that hangs on a failure are the recurring mistakes. Barriers, an invariant assertion, repetition, the race detector, and bounded waits address them.

Conclusion

Concurrent tests flake when they depend on timing. Control the interleaving with barriers, assert an invariant that must hold under contention, repeat and stress to expose a race, and run the race detector so an unsynchronized access is flagged. Self-check by removing the synchronization and asserting the test fails, and by running under the detector with no report. Then a passing concurrent test means the protection works, not that the timing happened to hide the bug.

Sources: Go: Data race detector, MDN: Concurrency model and the event loop, Java: Concurrency testing and stress testing.

FAQ

Why do concurrent tests flake?
They rely on timing: a sleep assumes the other operation has reached a point, and under load it has not, so the interleaving the test intended never happens and the assertion is about a different execution. A barrier removes the timing assumption by making one operation wait until the other is ready.
Does a passing concurrent test prove there is no race?
No. A race may not appear in a given run, so a passing test is no guarantee. Run the case under stress and use the race detector, which flags the unsynchronized access even when the result of one run looks correct.

Related Examples