0%
Concurrency and Async Programming: Threads, Locks, Event Loops, and Backpressure
Foundations
Synchronization
Concurrency Patterns
Testing and Debugging Concurrent Code
Concurrency bugs are among the hardest defects in software, not because they are complicated once understood, but because they appear rarely, vanish when observed and depend on timing that tests do not control. This section explains why these bugs hide, what kinds there are and why ordinary testing practices miss them, setting up the tools and techniques in the rest of the lesson.
The interleaving explosion
A concurrent program can run in many different orders. Two threads that each execute 10 atomic steps can interleave in 184756 different ways, the number of ways to choose 10 positions out of 20, and three threads of 10 steps each have more than five trillion interleavings. A bug may appear in only a handful of them. A normal test run executes one interleaving, chosen by the scheduler, and repeated runs tend to execute the same few, because the scheduler, caches and timing on a given machine are fairly consistent. This is why a test can pass ten thousand times on a developer laptop and fail on the first day in production, where different core counts, load and timing explore other interleavings. Concurrency testing is therefore about exploring interleavings deliberately, either by perturbing timing, by controlling the scheduler or by reasoning about all orders at once, rather than hoping that repetition will find the bad one.
Heisenbugs
A Heisenbug is a bug that changes or disappears when someone tries to observe it. Concurrency bugs are the classic example: adding a print statement or a log line introduces I/O, locks and delays that change the timing, so the race that caused the bug no longer happens. Attaching a debugger stops threads at breakpoints, which completely alters their relative order. Building with optimizations off changes which values stay in registers and which go to memory, so a missing memory barrier may stop mattering. Even running on a different machine or with a different number of cores can hide or reveal the bug. This means the usual debugging loop of reproducing, adding output and narrowing down often fails. Effective approaches either avoid changing timing, such as lightweight tracing into memory buffers and post mortem analysis of core dumps, or embrace control of timing, such as deterministic schedulers and record and replay tools that reproduce one exact execution.
A taxonomy of concurrency bugs
Concurrency bugs fall into a few families. Data races occur when two threads access the same memory without synchronization and at least one writes, which in languages such as C, C++ and Rust unsafe code is undefined behaviour, and in Java and Go leads to unexpected values. Atomicity violations occur when code assumes a sequence of operations runs without interruption but another thread intervenes, as in check then act and read modify write bugs, even when each individual access is synchronized. Order violations occur when code assumes one event happens before another, such as using an object before another thread has initialized it. Deadlocks occur when threads wait for each other in a cycle, livelocks when they keep reacting to each other without progress, and starvation when some thread never gets a turn. A study of real world concurrency bugs by Lu and colleagues found that almost all non deadlock bugs were atomicity or order violations, and most involved only two threads, which is encouraging for testing.
Why unit tests pass
Typical unit tests are written in ways that make concurrency bugs very unlikely to appear. They run on one thread, or start a few threads that each do a small amount of work and finish before the next even starts, because starting a thread takes longer than the work. They use mocks that return instantly, removing the delays that open windows for races. They run on lightly loaded machines with predictable scheduling. And they check results only at the end, so a transient invariant violation in the middle is never seen. Tests that do find concurrency bugs share the opposite properties: they start all threads together, often using a barrier or latch so that work begins at the same instant, run many operations per thread, add deliberate delays at critical points, run under load or on many cores, and check invariants continuously or after each operation. Even then, a passing test is evidence, not proof, which is why the techniques that follow add tools, control and design changes on top of testing.
Flaky tests are often real bugs
A flaky test, one that sometimes passes and sometimes fails with no code change, is frequently dismissed as a problem with the test environment and retried until it passes. For concurrent code, this habit throws away the most valuable signal a team ever gets: a flaky failure is often the only time a rare interleaving has been observed outside production. Studies of flaky tests at Google and in open source projects found that asynchronous waits and concurrency were among the leading causes. Some of those are bugs in the test, such as a sleep that assumes work finishes within 100 milliseconds, but many reveal real races in the code under test. A better policy is to record every flaky failure with its logs, quarantine the test rather than silently retrying it, and investigate whether the failure reveals a bug, ideally by rerunning it many times under a race detector or with perturbation. Replacing sleeps in tests with explicit synchronization, such as waiting for a condition, a latch or a future, removes most test caused flakiness and leaves only the failures worth investigating.
Memory model surprises
Some bugs only make sense once the memory model is taken into account. Processors and compilers reorder memory operations for speed, as long as a single thread cannot tell the difference, so another thread can observe writes in a different order from the one written in the code. On x86, stores can be delayed behind later loads; on ARM and POWER, almost any reordering is allowed without barriers. A test that passes on a developer laptop with an x86 chip can therefore fail on an ARM server or a phone, and a bug can appear only after a compiler upgrade enables a new optimization. Language memory models, such as those of Java, C++ and Go, define which reorderings are visible and promise sequential consistency only for programs free of data races. That is why removing data races matters even when the race looks harmless: once a race exists, the program may observe orders that no reading of the source code would suggest, and testing on one architecture says little about another.
Testing pyramids for concurrency
A sensible testing strategy for concurrent systems layers several techniques, each catching what the others miss. At the base, static analysis and type systems run on every change and remove whole classes of mistakes cheaply. Next come unit tests of pure logic, which cover behaviour without any concurrency. Above them sit focused concurrency tests for each shared component, run under a race detector and with stress or controlled scheduling. Then integration tests run the real system with realistic concurrency, and load and fault injection tests push it beyond normal conditions. At the top, production monitoring, tracing and incident analysis catch what slipped through and feed new tests back into the lower layers. Each layer is cheaper and faster than the one above, so the aim is to push detection as low as possible: a race found by a type checker costs seconds, the same race found in production costs an incident.
Concurrent programs have far more orders than tests can execute, and observing them changes timing. Most real bugs are atomicity or order violations between two threads. Write tests that start threads together, run many operations and check invariants often, and use tools that control or analyse timing rather than repetition alone.