Concurrency, Synchronization & Deadlock Questions
Correctness of shared-state coordination between concurrent threads and tasks. Covers mutexes (futex-based and spin-then-sleep), semaphores, condition variables, spinlocks, reader-writer locks, and the producer-consumer pattern; atomic operations, compare-and-swap, lock-free and wait-free structures with the ABA problem and safe memory reclamation; memory ordering, barriers and acquire/release semantics; race conditions, data races, critical sections, time-of-check to time-of-use gaps and read-modify-write hazards; deadlock (the Coffman conditions, lock ordering, prevention and detection), livelock and starvation; priority inversion as a locking hazard and the priority-inheritance fix; designing thread-safe structures such as bounded queues, caches, rate limiters, event buses and work-stealing schedulers, with coarse versus fine-grained and per-key locking; alternatives to locking such as thread confinement, message passing, actors and transactional memory; and diagnosing and testing concurrency bugs (heisenbugs, race detectors, stress and replay, reviewing concurrent code). Excludes a specific language's threading API and memory model, concurrency for throughput and pool tuning, distributed locks and consensus, database isolation levels, RTOS ceiling protocols and schedulability, and interrupt masking between ISRs and main code.
How do you test concurrent code systematically? Cover unit, stress and integration approaches, and how you reduce flakiness in CI while still exposing real races and deadlocks.
Sample Answer
Direct answer
Test concurrent code on three levels with different jobs. Unit tests check the logic single-threaded and use controlled interleavings (a gate that makes thread two run exactly between thread one's steps) to prove specific races are handled. Stress tests release many threads at once against invariants (a property that must always hold, such as "an item is created once" or "events in equals events out"), repeat many rounds, perturb the schedule, and run with a race detector. Integration tests run the real components together at realistic concurrency with every wait bounded by a timeout. Flakiness is handled by removing the cause (sleep-based waiting, shared global state, hidden timing assumptions), not by rerunning until green, and a flaky failure is logged with enough information (seed, thread dump) to be replayed.
Why a race detector alone is not a test
A race detector finds data races (unordered conflicting accesses). It does not find atomicity violations: code where every access is locked but a check and the action based on it are in two separate critical sections. You need both an invariant test and a detector. The following Go package shows each case. Go runs concurrent work in goroutines (lightweight threads managed by Go's runtime); -race is Go's built-in race detector; runtime.Gosched() asks the scheduler to pause the current goroutine and let others run, which is used below to widen the window between a check and its action.
package registry
import "sync"
type Registry struct {
mu sync.Mutex
m map[string]int
}
func New() *Registry { return &Registry{m: map[string]int{}} }
func (r *Registry) get(k string) (int, bool) {
r.mu.Lock()
defer r.mu.Unlock()
v, ok := r.m[k]
return v, ok
}
func (r *Registry) put(k string, v int) {
r.mu.Lock()
defer r.mu.Unlock()
r.m[k] = v
}
// Every access is locked, so the race detector sees no data race,
// but check and insert are two separate critical sections.
func (r *Registry) GetOrCreateBroken(k string, create func() int) int {
if v, ok := r.get(k); ok {
return v
}
v := create()
r.put(k, v)
return v
}
// Check and insert happen inside one critical section.
func (r *Registry) GetOrCreate(k string, create func() int) int {
r.mu.Lock()
defer r.mu.Unlock()
if v, ok := r.m[k]; ok {
return v
}
v := create()
r.m[k] = v
return v
}
package registry
import (
"runtime"
"sync"
"sync/atomic"
"testing"
)
// hammer releases n goroutines at the same instant and counts how many ran create().
func hammer(n int, get func(r *Registry, create func() int) int) int64 {
r := New()
var creates int64
start := make(chan struct{})
var wg sync.WaitGroup
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-start
get(r, func() int { atomic.AddInt64(&creates, 1); return 1 })
}()
}
close(start)
wg.Wait()
return creates
}
func TestBrokenCreatesOnce(t *testing.T) {
for round := 0; round < 200; round++ {
runtime.Gosched()
n := hammer(8, func(r *Registry, c func() int) int {
// Gosched inside create() yields the CPU in the gap between the check and the put
return r.GetOrCreateBroken("k", func() int { runtime.Gosched(); return c() })
})
if n != 1 {
t.Fatalf("round %d: create() ran %d times, want 1", round, n)
}
}
}
func TestFixedCreatesOnce(t *testing.T) {
for round := 0; round < 200; round++ {
if n := hammer(8, func(r *Registry, c func() int) int { return r.GetOrCreate("k", c) }); n != 1 {
t.Fatalf("round %d: create() ran %d times, want 1", round, n)
}
}
}
func TestPlainCounterRace(t *testing.T) {
var n int
var wg sync.WaitGroup
for i := 0; i < 2; i++ {
wg.Add(1)
go func() { defer wg.Done(); for j := 0; j < 1000; j++ { n++ } }()
}
wg.Wait()
_ = n
}
Run in a Linux container (Go 1.23, with a go.mod for module registry) with go test -race -run Broken -count=1 ., go test -race -run Fixed -count=1 ., and go test -race -run PlainCounter -count=1 .:
== -race, broken GetOrCreate only
--- FAIL: TestBrokenCreatesOnce (0.00s)
registry_test.go:37: round 0: create() ran N times, want 1
FAIL
== -race, fixed GetOrCreate only
ok registry
== -race, plain counter
WARNING: DATA RACE
GetOrCreateBrokenlocks every map access, so-raceprints no report for it, but the invariant test fails: the release gate (startchannel) makes 8 goroutines pass the check together, and aruntime.Gosched()inside the gap yields the CPU so the others also see "missing". The countNin the message varies per run, anywhere from 2 up to the 8 goroutines released, and the failure usually shows up in round 0; the test failed in every re-run tried. The test callsGetOrCreateBrokenitself, with theGoschedplaced inside thecreatecallback, which runs in the gap between the check and the insert. That yield is what makes the failure dependable: with it removed, the same test passes on some runs and fails on others, so a stress test needs the schedule perturbation as well as the start gate.GetOrCreatedoes the check and insert in one critical section; the same test passes. Note the trade-off: it holds the mutex whilecreateruns, which is fine for a cheap constructor but serializes all keys behind one slow call, so for an expensivecreateuse a per-key once or future instead.TestPlainCounterRacehas no assertion at all and would pass on a normal run, but-racereportsWARNING: DATA RACE, because two goroutines incrementnwithout synchronization.
The levels
- Unit: keep the concurrent logic small, with an injectable executor or clock (the code receives the thing that runs its tasks or tells the time as a parameter, so a test can swap in a controlled one) so a test can run tasks in a chosen order. For mobile modules, use the platform's test executor or a single-threaded test dispatcher, so the callback order is fixed and no real sleep is involved. In Kotlin, for example,
runTestfromkotlinx-coroutines-testwith aStandardTestDispatcherqueues launched coroutines and runs them only when the test advances them (advanceUntilIdle()), anddelaycalls are skipped using virtual time, so the test chooses the order and never really waits. Test the invariant for each operation pair: put/put, put/get, close/put. - Stress: (a) a start gate so all workers start in the same instant; (b) more threads than cores (oversubscription), because the operating system must then pause threads mid-operation in awkward places; (c) 100 or more rounds, each with fresh state; (d) a schedule perturbation (
Gosched, a random tiny sleep,tasksetto a different core count); (e) always run under the detector (-racein Go, ThreadSanitizer in C and C++); in Go,-count=Nrepeats each test N times, which is how rounds are multiplied; (f) check invariants after every round. - Integration: the real storage, queue and thread pool, at production thread counts, with a timeout on every wait so a deadlock fails the test with a thread dump instead of hanging CI (continuous integration, the automated build and test server).
Reducing flakiness in CI while still exposing real bugs
- Never wait with
sleep(100ms)to mean "the other thread is done". Use a latch (a one-shot gate that opens when a count reaches zero), a future (a handle to a result that arrives later) or a channel; those either complete or time out with a message. - Log the random seed and parameters of each failing stress run so it can be replayed. A failing test gets a thread dump on timeout.
- Split the budget: pull requests run
go test -race -count=1on a quick suite (seconds); a nightly job runs the stress suite with a high-countand large thread counts. Flakes found nightly become bugs with owners. - Do not auto-retry a failing concurrency test and mark it passed: a test that fails 1 time in 200 is reporting a real interleaving, and retries delete the evidence. Quarantine a test (move it to a separate suite that does not block merges) only with an owner and a deadline, and never delete it.
- Isolate shared state: each test builds its own objects, ports and temp directories, so one test's thread cannot disturb another's.
Trade-offs and pitfalls
- A stress test that passes is evidence, not proof; a deterministic injection test is the only kind that proves a specific interleaving is handled.
- Heavy stress on a busy CI machine creates false timeouts: make timeouts generous and relative (scaled to measured speed), and run the heavy tier on a dedicated runner.
- Using
-raceeverywhere multiplies CI time by 2x to 20x (Go's documented range), which is another reason to keep the fast tier small.
How can thread confinement and message passing help you avoid locks? Give an example of confining state to one thread or queue, and say when you would still need synchronization.
Sample Answer
Direct answer
If only one thread ever touches a piece of data, nothing can race on it, so it needs no lock. Thread confinement means giving each piece of mutable state exactly one owning thread (or one serial queue). Message passing means every other thread asks the owner to act by putting a message on a queue, instead of reaching into the data. The queue is then the only place threads meet, and it carries its own synchronization. You still need real synchronization at that queue, for data that is genuinely shared, and for anything that escapes the owner by pointer.
How it removes the lock
- Pick the owner: a dedicated thread, a goroutine (Go's lightweight thread, started with the
gokeyword), or a serial dispatch queue (a queue, as in Apple's Grand Central Dispatch, that runs its tasks strictly one after another). - The owner is the only code that holds a reference to the state.
- Other threads send small command or event messages.
- The owner processes messages one at a time, so every operation on the state is already atomic with respect to every other operation.
The queue itself is synchronized by the language runtime. In Go a queue between goroutines is a channel, and a send on a channel is synchronized before the corresponding receive completes (Go memory model, go.dev/ref/mem), which means everything the sender wrote before sending is guaranteed visible to the receiver. Java documents the same kind of guarantee, called happens-before (an action that happens-before another is guaranteed to be visible to it), for concurrent collections: actions before placing an object into one happen-before actions after taking it out in another thread.
Two familiar examples. The Android UI toolkit is not thread-safe, and its developer documentation tells you not to access it from outside the UI thread: the main thread owns every view, and worker threads post results to it. A server can give one goroutine ownership of a counter map and let request handlers send events to it.
Worked example, run with the Go race detector
The Go syntax to know: <-chan event is a channel the function may only receive from and chan<- map[string]int one it may only send on; for e := range in receives until the channel is closed; defer wg.Done() runs when the function returns, telling the WaitGroup (a counter the main goroutine waits on) that one worker has finished. The owner goroutine below is the only code that touches counts. Four goroutines send 1,000 events each. When the owner finishes it sends the whole map to the receiver and never touches it again, which is a clean hand-over of ownership. The second half shows the hole in the pattern: a message that carries a pointer.
package main
import (
"fmt"
"os"
"sync"
)
// Confinement: only the owner goroutine ever touches counts. Everyone else sends a message.
type event struct{ word string }
func owner(in <-chan event, done chan<- map[string]int) {
counts := map[string]int{} // confined: no other goroutine has a reference
for e := range in {
counts[e.word]++
}
done <- counts // ownership of the map transfers to the receiver; owner never touches it again
}
// The hole: a message that carries a pointer lets sender and receiver share memory.
type buf struct{ data []int }
func main() {
in := make(chan event, 16)
done := make(chan map[string]int)
go owner(in, done)
var wg sync.WaitGroup
for w := 0; w < 4; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 1000; i++ {
in <- event{"hit"}
}
}()
}
wg.Wait()
close(in)
fmt.Println("confined counter:", (<-done)["hit"])
// Escaped pointer: sender keeps writing to a buffer it already sent.
if len(os.Args) > 1 && os.Args[1] == "leak" {
ch := make(chan *buf, 1)
b := &buf{data: make([]int, 4)}
ch <- b
var wg2 sync.WaitGroup
wg2.Add(1)
go func() { defer wg2.Done(); r := <-ch; r.data[0] = 1 }()
b.data[0] = 2 // sender still writes after sending: shared, unsynchronized
wg2.Wait()
fmt.Println("leaky version finished")
} else {
ch := make(chan *buf, 1)
b := &buf{data: make([]int, 4)}
b.data[0] = 2
ch <- b
b = nil // the sender gives up its reference after sending
var wg2 sync.WaitGroup
wg2.Add(1)
go func() { defer wg2.Done(); r := <-ch; r.data[0] = 1; fmt.Println("receiver wrote", r.data[0]) }()
wg2.Wait()
}
}
Run in a golang:1.23 container with go run -race confine.go:
confined counter: 4000
receiver wrote 1
Running go run -race confine.go leak takes the other branch, where the sender keeps writing to a buffer after sending its pointer. The race detector reports a data race between two writes, one on the receiver goroutine (line 48) and one on the main goroutine (line 49). The report appeared on each of a dozen re-runs; the address, the goroutine numbering and which of the two writes is listed as the earlier one can differ between runs, because that depends on which goroutine gets there first. The report is written to standard error the moment the detector sees the second unordered access, so it appears before the program's own last print, leaky version finished:
confined counter: 4000
==================
WARNING: DATA RACE
Write at 0x00c000142000 by goroutine 12:
main.main.func2()
/w/confine.go:48 +0xac
Previous write at 0x00c000142000 by main goroutine:
main.main()
/w/confine.go:49 +0x600
Goroutine 12 (running) created at:
main.main()
/w/confine.go:48 +0x5dc
==================
leaky version finished
Found 1 data race(s)
exit status 66
Read it as: the two stacks name the two unordered writes to the same address (r.data[0] = 1 in the receiver, b.data[0] = 2 in main), and exit status 66 is how go run reports that the race detector fired. Here the file is named confine.go and /w is the container's working directory. The channel gave an ordering for what happened before the send, but the sender's later write has no ordering with the receiver's write.
What stays shared even when every buffer is per-thread
The first two items cause wrong results in everyday code, so check them first; the last three are narrower, mostly performance or special contexts.
- Escaped pointers. Sending a pointer, slice or reference shares the memory. Either send a copy, or treat the send as a transfer and drop your own reference, as the non-leaking branch does.
- Static and global state. A function-local variable is confined; a global, a singleton (the one shared instance of a class) or a
staticis not, no matter which thread's code touches it. - The allocator. The allocator is the runtime component behind
mallocornewthat hands out memory. Each thread's buffer comes from a shared heap. Allocators synchronize internally (often with per-thread caches), so this is correct, but heavy allocation from many threads still contends, and freeing memory from a thread other than the one that allocated it can be slower. - False sharing. The cache line is the block of memory (typically 64 bytes) that cores copy between their caches, and a core must own the whole line to write any byte of it. Two threads' private counters that sit in the same cache line make the cores fight over that line. Results stay correct but throughput collapses. Pad or align per-thread data to separate lines.
- Signal handlers. A signal interrupts a thread and runs on top of it. Confinement does not protect that thread's data from its own handler, and only a small set of async-signal-safe functions (the short list of functions the system documents as safe to call from inside a handler, because each is either reentrant or cannot be interrupted by a signal handler; functions like
mallocandprintfare not on it, since a handler could interrupt them while they hold an internal lock) may be called inside one.
When you still need synchronization
- At the queue: its enqueue and dequeue must be thread-safe (the runtime's channels and concurrent queues are).
- For read-mostly data many threads share (a configuration object): publish an immutable copy through an atomic reference rather than confining it.
- When one operation spans two owners, such as moving money between two accounts owned by different threads: either have one owner coordinate with a two-step message exchange, or take locks in a fixed order.
- When owners wait for each other: if owner A sends a request to owner B and blocks for the reply while B does the same to A, you have a deadlock built from queues instead of locks.
Trade-offs
Confinement trades locks for latency and for a bottleneck: all work on that state is serial, and an owner that blocks on slow I/O stalls everyone waiting on it. Keep owner handlers short, bound the queue so a flood applies backpressure (senders are forced to wait or are refused when the queue is full) instead of filling memory, and move slow work to other threads that report back by message.
Two threads each run counter += 1 on a shared integer many times, and the final total is sometimes too low. Explain exactly how the interleaving loses updates, and show how you would fix it. When would you choose a lock and when an atomic?
Sample Answer
Direct answer
counter += 1 is not one operation. The hardware does a load, an add and a store, and a second thread can run its own load between your load and your store. Both threads then compute from the same old value and one increment is overwritten (a lost update). Fix it by making the read-modify-write indivisible: protect it with a mutex, or use an atomic increment instruction. Choose an atomic for a single independent word; choose a lock when more than one variable or a check-then-act must change together.
Exactly how the interleaving loses an update
Here is what the compiler produced for void inc(void) { counter += 1; } with gcc:14 on aarch64 (gcc -O0 -S, then -O2 -S). The -O0 listing is adrp/add/ldr/add/adrp/add/str; at -O2 it is shorter but is still one load, one add and one store:
inc: (gcc -O2, aarch64)
adrp x1, .LANCHOR0
ldr x0, [x1, #:lo12:.LANCHOR0] ; load counter
add x0, x0, 1 ; add 1 in a register
str x0, [x1, #:lo12:.LANCHOR0] ; store back
ret
Reading the listing: adrp loads the address of the 4 KB memory page that holds counter into register x1 (a register is one of the CPU's few fast storage slots); :lo12:.LANCHOR0 is the low 12 bits of the address, the offset inside that page, so [x1, #:lo12:.LANCHOR0] means "the memory at the counter's address". x0 is the register that does the arithmetic. The comments mark the three separate steps: load, add, store.
Starting from counter = 5:
| Step | Thread T1 | Thread T2 | counter in memory |
|---|---|---|---|
| 1 | load 5 | 5 | |
| 2 | load 5 | 5 | |
| 3 | add: 6 (register) | add: 6 (register) | 5 |
| 4 | store 6 | 6 | |
| 5 | store 6 | 6 |
Two increments ran, the value moved from 5 to 6. The window is only a few instructions wide, so any single increment is rarely hurt, but a million of them make it near-certain that some are.
Why it is intermittent
The loss needs the scheduler to switch threads, or another core to touch the cache line (the small block of memory, commonly 64 bytes, that cores hold in their private caches and hand to each other; only one core at a time may write it), inside that tiny window. Different runs interleave differently, and anything that changes timing (a print, a debugger, a different compiler flag) changes how often it happens. Below, five runs of the same program lost different amounts.
The fixes, compared in one harness
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
#define N 1000000
static long plain = 0;
static long locked = 0;
static atomic_long atom = 0;
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
static void *work(void *arg) {
(void)arg;
for (int i = 0; i < N; i++) {
plain += 1; /* data race */
pthread_mutex_lock(&m); locked += 1; pthread_mutex_unlock(&m);
atomic_fetch_add_explicit(&atom, 1, memory_order_relaxed);
}
return NULL;
}
int main(void) {
pthread_t t[2];
for (int i = 0; i < 2; i++) pthread_create(&t[i], NULL, work, NULL);
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
printf("expected=%d plain=%ld locked=%ld atomic=%ld\n", 2 * N, plain, locked, atom);
return 0;
}
gcc -O0 -pthread counter.c -o c && ./c, five runs in a gcc:14 container (aarch64):
expected=2000000 plain=1975751 locked=2000000 atomic=2000000
expected=2000000 plain=1986956 locked=2000000 atomic=2000000
expected=2000000 plain=1998485 locked=2000000 atomic=2000000
expected=2000000 plain=1954567 locked=2000000 atomic=2000000
expected=2000000 plain=1982365 locked=2000000 atomic=2000000
Under -fsanitize=thread the plain line is reported as a data race at counter.c:13 and the locked and atomic lines print 2000000 with no report. (I used memory_order_relaxed for the atomic. A memory order says how much an atomic operation also orders the surrounding reads and writes: relaxed promises only that the operation itself is indivisible; acquire/release is the pairing used to hand other data from one thread to another; sequentially consistent, the default, makes all threads agree on one order for all such operations. The counter publishes no other data, so only the atomicity of the increment matters here.)
Which hardware instruction backs the atomic
The atomic increment compiles to a single indivisible read-modify-write, and which one depends on the target. From gcc:14: on x86-64 (--platform linux/amd64, -O2) it is lock addq $1, counter(%rip); on aarch64 with -march=armv8-a -mno-outline-atomics it is a load-exclusive / store-exclusive loop (ldxr, add, stxr, cbnz back if the store failed); with -march=armv8.1-a it is one ldadd. Reading these: lock addq is an ordinary add to memory with a lock prefix that makes the whole read-modify-write indivisible. ldxr loads the value and marks the location as exclusively watched by this core, stxr stores only if nobody wrote the location since and writes a success flag, and cbnz (compare and branch if nonzero) jumps back to retry when that flag says the store failed; so the exclusive pair retries if another core wrote the location in between. ldadd does the whole atomic add in one instruction. These instruction names are context for how hardware provides the guarantee; what matters is that the hardware offers one indivisible read-modify-write.
Lock or atomic
- Atomic: one word, one independent operation (counter, flag, sequence number, pointer swap). No sleeping, no lock to forget to release, safe from signal handlers (functions the OS runs asynchronously, interrupting your thread, when a signal arrives) and, for lock-free types (atomic types implemented with real atomic instructions rather than a hidden lock;
is_lock_free()tells you), interrupt handlers. - Mutex: more than one variable must change together, or you have check-then-act ("increment only if below the cap"), or the critical section calls other code. Two separate atomic variables are never one atomic update:
AtomicInteger usedandAtomicInteger limitread one after the other still allow another thread's change in between (the same holds forAtomicIntegeron Android: each call is atomic, a sequence of calls is not). - Under contention (many threads using the same variable at the same time) both serialise on the same cache line. A contended mutex can additionally put a waiting thread to sleep in the kernel and wake it later, which costs context switches; an atomic add just waits for the cache line. When one counter is hot, the usual real fix is neither: keep a counter per thread (or per shard, one of several independent slices of the data) and sum when read, so threads stop sharing the line. I did not time these variants here, so the comparison above is a reasoning claim, not a measurement.
- Shared cache (a map plus eviction order): the invariant spans several fields, so use a lock (sharded by key to reduce contention). A lock-free repair is realistic for one counter or one pointer, not for an invariant over a whole structure.
Pitfalls
volatiledoes not makecounter += 1atomic; it only stops the compiler from caching the value.- On an embedded target the same loss occurs between a task and an interrupt service routine; the fix there is a brief interrupt mask or a hardware atomic, not a mutex that the ISR cannot take.
- Reading the final value after
pthread_joinis safe because join orders the writes before the read.
One thread appends to a shared list while another iterates over it and removes elements. Describe the data race, what failures you would actually see, and how you would fix it without making iteration painfully slow.
Sample Answer
Direct answer
Appending to a list while another thread iterates and removes from it is a data race: two threads access the same memory, at least one writes, and nothing orders the accesses. For java.util.ArrayList the Javadoc says it is not synchronized and any structural modification (a change to the list's size, such as adding or removing elements, as opposed to just replacing a value) from concurrent threads must be synchronized externally. What you see is most often a ConcurrentModificationException, but that exception is only best-effort detection, so lost elements, wrong sizes or other corruption are possible without any exception at all. Fix it with a concurrent collection chosen for the access pattern (for example CopyOnWriteArrayList when reads and iteration vastly outnumber writes), or a lock held for short snapshots, so iteration is not slowed down.
What actually happens
An ArrayList keeps an array plus a size counter and a modification counter. add writes into the array and bumps the counters; iterator.remove() shifts later elements left. When two threads do this at once, the writer can change the list's structure under the reader's iterator.
- The iterator notices the modification count changed and throws
ConcurrentModificationException. The Javadoc is explicit that this fail-fast behaviour cannot be guaranteed and exists only to detect bugs. A run with no exception does not prove the code is correct. - Without the check firing, the possible outcomes include skipped or repeated elements, a removal applied to the wrong element, or an element lost because two threads' updates to
sizeinterleaved. The Javadoc makes no promise about any of them.
A tiny trace of the fail-fast check, with illustrative counter values: after three add calls the list [a, b, c] has a modification count of 3. A reader calls iterator(); the iterator copies that count as the one it expects (3). The writer then adds d, so the list's count becomes 4. On its next next() call the iterator compares the list's count (4) with the one it expects (3), sees they differ, and throws ConcurrentModificationException. (The iterator's own remove() updates the expected count too, so only changes made by someone else trip the check.) Because the check runs only when next() is called and only compares counts, a race that does not happen to change the count where the iterator looks goes unnoticed, which is why the Javadoc calls it best-effort.
Measured in a Temurin 21 container (program below): the program retries the racy version up to 20 times and stops at the first failure; the reader thread died with ConcurrentModificationException within those attempts.
Options for the fix
Copy-on-write means every change builds a fresh copy of the underlying array and swaps it in, so readers keep using the old array untouched.
| Option | Iteration cost | Write cost | Fits when |
|---|---|---|---|
Collections.synchronizedList plus synchronized (list) { ... } around every iteration | Blocks writers for the whole loop | Short lock per call | Small lists, short loops. The Javadoc says you must manually synchronize on the list while iterating, or behaviour is non-deterministic. |
CopyOnWriteArrayList | Lock-free snapshot (a frozen copy of the contents as of one moment): the iterator uses the array as it was when created and never throws ConcurrentModificationException | Every add or remove copies the whole array | Reads and iteration vastly outnumber writes (listeners, configuration). The Javadoc calls mutation "ordinarily too costly". |
| Lock, copy a snapshot, iterate the copy outside the lock | Iteration runs unlocked on private data | Short lock | Moderate write rate, and a slightly stale view is acceptable |
ConcurrentLinkedQueue or ConcurrentHashMap.newKeySet() | Weakly consistent iterators (they never throw and always give a valid view, but may or may not show changes made after they were created): no exception | Cheap | You do not need index access or ordering by position |
Recommendation for the situation described (frequent appends, a sweeper that removes): if appends are rare compared with sweeps, CopyOnWriteArrayList with removeIf, because iteration stays fast. If appends are frequent, copy-on-write gets expensive (each append copies all n existing elements, so the total copying grows with the square of the list size: growing a list to n elements one append at a time copies 0 + 1 + ... + (n - 1) = n(n - 1)/2 elements, which is 3 for n = 3, 499,500 for n = 1,000 and 49,995,000 for n = 10,000, so ten times more elements means about a hundred times more copying), so use a queue or concurrent set, or the lock-and-snapshot pattern.
Executed demonstration
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
public class ListRace {
// Writer appends 0..N-1. Reader repeatedly sweeps the list removing even numbers.
static boolean broken(List<Integer> list) throws Exception {
final int N = 20_000;
AtomicBoolean failed = new AtomicBoolean();
Thread writer = new Thread(() -> {
for (int i = 0; i < N; i++) list.add(i);
});
Thread reader = new Thread(() -> {
try {
for (int sweep = 0; sweep < 200; sweep++) {
for (Iterator<Integer> it = list.iterator(); it.hasNext(); ) {
if (it.next() % 2 == 0) it.remove();
}
}
} catch (RuntimeException e) {
failed.set(true);
System.out.println(" reader died with " + e.getClass().getSimpleName());
}
});
writer.start(); reader.start(); writer.join(); reader.join();
return failed.get();
}
public static void main(String[] args) throws Exception {
System.out.println("plain ArrayList:");
boolean sawFailure = false;
for (int run = 0; run < 20 && !sawFailure; run++) {
sawFailure = broken(new ArrayList<>());
}
System.out.println(" failure observed = " + sawFailure);
// Fix: CopyOnWriteArrayList. Iterators work on a snapshot, removal goes through removeIf.
CopyOnWriteArrayList<Integer> cow = new CopyOnWriteArrayList<>();
Thread writer = new Thread(() -> { for (int i = 0; i < 20_000; i++) cow.add(i); });
Thread sweeper = new Thread(() -> {
for (int s = 0; s < 200; s++) cow.removeIf(x -> x % 2 == 0);
});
writer.start(); sweeper.start(); writer.join(); sweeper.join();
cow.removeIf(x -> x % 2 == 0); // final sweep after the writer is done
boolean allOdd = cow.stream().allMatch(x -> x % 2 == 1);
System.out.println("COW: size = " + cow.size() + ", all odd = " + allOdd);
}
}
Output (Temurin 21, java ListRace.java; run twice with the same result):
plain ArrayList:
reader died with ConcurrentModificationException
failure observed = true
COW: size = 10000, all odd = true
The copy-on-write version keeps 10,000 elements: the writer appends 0 through 19,999, and removing every even number leaves the 10,000 odd ones. Note the fix uses removeIf on the list rather than iterator.remove(), because the Javadoc says a copy-on-write iterator's remove, set and add throw UnsupportedOperationException. In the program, removeIf runs again after the writer finishes, so the final state is deterministic whatever the interleaving.
Pitfalls
- Catching
ConcurrentModificationExceptionand retrying is not a fix: the exception is not guaranteed to occur. - Locking only the writer does nothing for a reader that iterates without the lock.
- A
size()check followed byget(i)on a concurrent list is again a check-then-act race: the list can shrink between the two calls. - Android and Kotlin code on the JVM hits the same rule with the same collections; Swift arrays are value types but a shared variable holding an array is still a data race when two threads mutate it.
A concurrency bug disappears when you add logging, or only occurs in release builds on one device. Why does that happen, and how do you still reproduce it deterministically?
Sample Answer
Direct answer
A concurrency bug that vanishes when you add logging or appears only in a release build on one device is almost always a data race (two threads touch the same variable, at least one writes, and nothing orders them), and the symptom depends on things that the observation changes. Three mechanisms: (1) the compiler optimizer may assume a plain variable is not changed by another thread and keep it in a register or hoist a read out of a loop (release builds optimize, debug builds do not); (2) the CPU may reorder memory operations, and different CPU architectures and core counts reorder differently; (3) timing: logging, a debugger or a breakpoint adds locks, system calls and delay, which shifts which interleaving occurs. To reproduce deterministically: use a tool that flags the race without needing the bad timing (ThreadSanitizer, TSan, a compiler-based tool that reports data races at run time), reproduce under the same optimization level and CPU architecture as the failure, force the interleaving with test hooks, and record the failing run if you can.
Why logging makes it disappear (and why the debugger does too)
Logging an error calls into a library that typically takes a lock. Locking and unlocking act as barriers (a barrier forbids the compiler and CPU from moving memory operations across it and makes earlier writes visible to the other threads that take the same lock). So the logging call accidentally supplies the synchronization the program lacks. It also slows one thread by microseconds, which can be enough to avoid the narrow window. A debugger stops threads and runs them one at a time, which removes parallelism.
Compiler hoisting: the flag that never changes
#include <atomic>
#include <chrono>
#include <cstdio>
#include <thread>
#if defined(USE_ATOMIC)
std::atomic<bool> stop{false};
#else
bool stop = false; // plain flag: a data race, so the compiler may assume nobody else writes it
#endif
long spin_until_stop() {
long n = 0;
while (!stop) {
n++;
#ifdef OPAQUE_CALL
std::fputc('.', stderr); // opaque library call: the compiler must assume it might change `stop`
#endif
}
return n;
}
int main() {
long n = 0;
std::thread worker([&] { n = spin_until_stop(); });
std::this_thread::sleep_for(std::chrono::milliseconds(200));
stop = true;
worker.join();
std::puts("worker saw the flag and exited");
(void)n;
}
Compiled with GCC 14 (aarch64 container); each run has a 3 second limit from timeout 3, and the commands are g++ -std=c++20 -O0 -pthread hoist.cpp -o h0 (and -O2, -O2 -DOPAQUE_CALL, -O2 -DUSE_ATOMIC, and -O1 -g -fsanitize=thread for the TSan run):
-O0, plain bool: worker saw the flag and exited (exit status 0)
-O2, plain bool: (no output, killed by timeout) (exit status 124)
-O2, plain bool + fputc in loop: worker saw the flag and exited (exit status 0)
-O2, std::atomic<bool>: worker saw the flag and exited (exit status 0)
TSan, plain bool: WARNING: ThreadSanitizer: data race
At -O2 the optimizer is allowed to assume no other thread writes stop, so it reads the flag once and compiles the loop into an infinite jump. GCC 14 for aarch64 at -O2 emits this for the worker function (label numbers differ between compiler versions and runs):
spin_until_stop():
adrp x0, .LANCHOR0
ldrb w0, [x0, #:lo12:.LANCHOR0] // read `stop` once
tbnz x0, 0, .L10 // if bit 0 is set, go to the exit
.L11:
b .L11 // branch to itself forever
.L10:
mov x0, 0
ret
Reading it: adrp puts the address of the 4 KB page that holds stop in register x0 (a register is one of the CPU's few fast storage slots), and :lo12: is the offset of stop inside that page. ldrb loads one byte (the bool) into w0. tbnz tests bit 0 of the value and jumps to .L10, the exit, only if it is set. If the flag was clear, execution falls into .L11: b .L11, a branch to its own address: no further load, so no way to see the flag change. That is the hoisting: the compiler moved the read out of the loop so it happens once. Adding a call the compiler cannot see through (fputc) forces it to reload the flag, so the "debug print" version works; that is the "disappears when I add logging" effect in its purest form. -O0 keeps the variable in memory because it does no optimization. (-O0, -O1 and -O2 are increasing optimization levels; a release build typically uses a high one, a debug build -O0.)
The same bug exists on phones in Java and Kotlin. A plain field such as boolean stopped read in a loop on another thread may be read once by the JIT compiler and never again, and a release build or a different runtime may hoist where a debug build did not. The fix is a volatile field (@Volatile in Kotlin) or an AtomicBoolean; in Swift, a plain Bool shared across threads is the same kind of data race, and you use a lock, an atomic or an actor.
volatile versus atomic: in C and C++, volatile makes the compiler perform every access, which would fix this one symptom, but it does not make the access atomic and gives no ordering between threads, so it is still a data race (undefined behaviour) and you should use std::atomic. (In Java and Kotlin, volatile does give visibility and ordering through the Java memory model, so do not carry the C++ rule across languages.)
Why one device only: CPU architecture and ordering
A tiny example: one thread runs data = 1; flag = 1; and another runs if (flag == 1) use(data);. x86-64 keeps stores in order so the reader never sees flag == 1 with old data; an Arm core may make flag = 1 visible first, so the reader sees the flag and reads stale data. x86-64 CPUs have a comparatively strong memory model; most ARM CPUs, including phones, are allowed to reorder loads and stores (a weak model), so a missing acquire/release pair that works on a developer's laptop fails on an ARM device. Core count, big.LITTLE (phone chips that combine fast and slow cores) and clock speed change the timing, so one device may reach the bad interleaving and another may not. A release build turns the optimizer on, and the optimizer is what hoists and reorders code.
How to reproduce it deterministically
- Detect the race instead of waiting for the symptom: build the exact release configuration (
-O2 -g) with ThreadSanitizer. TSan reports the conflicting accesses even on a run that does not misbehave, as it did on the flag above. - Bisect the variable: first by optimization level (
-O0,-O1,-O2; the lowest level that fails points to compiler reordering), then by file (compile suspect files unoptimized one at a time), then by CPU (run the same binary on an ARM device or emulator versus x86), then by commit withgit bisectdriven by a stress loop that runs the test many times. - Force the interleaving: add a test-only hook at the suspected gap that waits on a latch (a one-shot gate that blocks threads until a test opens it) so the test controls which thread goes first. A race that happens once in a million runs then happens every run.
- Record: on Linux,
rrrecords a failing run and replays it identically, so you debug the real failure instead of a vanished one. - Constrain the machine: pin threads to few cores (
taskset), or raise thread counts beyond core count, to push toward the production timing.
Pitfalls
Do not conclude the bug is fixed because a run with logging passes. Do not "fix" it with a sleep. Do not add volatile to a C++ shared variable and call it done.
Unlock Full Question Bank
Get access to all 7 Concurrency, Synchronization & Deadlock interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.