StackPractices
advanced By Mathias Paulenko

Race Condition Debugging Checklist

Checklist for identifying, reproducing, and fixing race conditions: symptoms, debugging tools, common patterns, and fixes with locks, atomics, and channels.

Overview

Race conditions happen when threads hit shared state without proper synchronization, and the outcome ends up depending on scheduling luck. They’re the worst kind of bug: intermittent, load-dependent, and often gone the moment you attach a debugger or add a log line.

Use this checklist when a test fails “sometimes”, when production shows impossible values, or when a bug vanishes every time you look at it. It walks through the full cycle — identifying symptoms, forcing a reproduction, picking the right debugging tool, matching the code to a known pattern, and applying the right fix. Sections 1-3 are diagnostic; sections 4-6 are where you fix things and keep them fixed.

Before you start: resist the urge to guess-fix. A synchronized sprinkled on a hunch usually hides the race instead of removing it, and it comes back under a different schedule. Reproduce first (section 2), then fix with a tool that can prove the race is gone (section 3).


1. Symptom Identification

Races almost never announce themselves. What you see is the fallout — a wrong value, a hang, a flaky test — and the cause is three stack frames away. Match what you’re seeing to the symptoms below before touching any code.

1.1 Common Symptoms

Symptom                          | Likely cause
─────────────────────────────────┼──────────────────────────────────────
Intermittent test failures       | Non-deterministic thread scheduling
Corrupted data / wrong values    | Lost updates or torn reads
Deadlocks / hangs                | Lock ordering inconsistency
High CPU with no progress        | Livelock or spin-wait
Memory corruption                | Unsynchronized writes to shared struct
Random crashes / segfaults       | Dangling pointer + concurrent free
Stale data in cache              | Missing memory barrier / visibility
Counter off by N                 | Non-atomic read-modify-write

1.2 Initial Triage Questions

- [ ] Does the bug reproduce intermittently (not every run)?
- [ ] Does it reproduce more under load?
- [ ] Does it disappear when you add logging?
- [ ] Does it disappear when you run single-threaded?
- [ ] Are there shared mutable variables accessed from multiple threads?
- [ ] Are there lazy initialization patterns (double-checked locking)?
- [ ] Are there compound operations (check-then-act) on shared state?
- [ ] Is there a global/static mutable variable?
- [ ] Are locks acquired in different orders in different code paths?
- [ ] Are there callbacks or event handlers that run on different threads?

2. Reproduction Strategies

Trigger a race on demand and you’re most of the way to fixing it. These three techniques cover most cases: brute-force stress, deterministic scheduling with barriers, and formal memory-model testing.

2.1 Stress Testing

import threading
import pytest

class Counter:
    def __init__(self):
        self.value = 0

    def increment(self):
        self.value += 1  # RACE CONDITION: read-modify-write is not atomic

def test_race_condition():
    counter = Counter()
    threads = []

    # High concurrency to trigger race
    for _ in range(100):
        t = threading.Thread(target=lambda: [counter.increment() for _ in range(1000)])
        threads.append(t)

    for t in threads:
        t.start()
    for t in threads:
        t.join()

    # If race condition exists, counter.value < 100000
    assert counter.value == 100000, f"Race detected: {counter.value} != 100000"

2.2 Controlled Reproduction with Barriers

import threading

def reproduce_race():
    shared = {}
    barrier = threading.Barrier(2)

    def writer():
        barrier.wait()  # Ensure both threads start simultaneously
        shared['key'] = 'value'

    def reader():
        barrier.wait()  # Ensure both threads start simultaneously
        return shared.get('key')  # May not see the write

    t1 = threading.Thread(target=writer)
    t2 = threading.Thread(target=reader)
    t1.start()
    t2.start()
    t1.join()
    t2.join()

Barriers turn “it happens sometimes” into “it happens on the first run”. Combine them with a loop — run the reproduction 10,000 times in CI and count any failure as a real bug, not a flake.

2.3 Java Concurrency Tests with jcstress

import org.openjdk.jcstress.annotations.*;
import org.openjdk.jcstress.infra.results.II_Result;

@JCStressTest
@Outcome(id = "1, 1", expect = Expect.ACCEPTABLE, desc = "Sequential")
@Outcome(id = "0, 1", expect = Expect.ACCEPTABLE, desc = "Writer first")
@Outcome(id = "1, 0", expect = Expect.ACCEPTABLE, desc = "Reader first")
@Outcome(id = "0, 0", expect = Expect.FORBIDDEN, desc = "Race condition")
@State
public class RaceConditionTest {
    int x = 0;
    int y = 0;

    @Actor
    public void actor1() {
        x = 1;
        y = 1;
    }

    @Actor
    public void actor2(II_Result r) {
        r.r1 = y;
        r.r2 = x;
    }
}

jcstress runs your actors under every legal interleaving the JVM can produce, including reorderings your CPU won’t do but the memory model allows. If (0, 0) shows up even once, the code is broken; the “forbidden” outcome is a real execution, not a theoretical one. For deeper JVM-level coverage, see the complete guide to Java concurrency.

Companion files: the race-condition-debugging-checklist companion repo packages the stress test, the barrier repro, the jcstress test and the Go -race demo as standalone runnable files, so you can trigger each race and watch the detector catch it.


3. Debugging Tools

3.1 Tool Selection

Language    | Tool                    | What it detects
────────────┼─────────────────────────┼──────────────────────────────
Java        | Thread Sanitizer (TSan) | Data races, deadlocks
Java        | jstack                  | Thread dumps, deadlock detection
Java        | jconsole / VisualVM     | Live thread monitoring
Java        | jcstress                | Concurrency correctness tests
Python      | threading.debug         | Thread state inspection
Python      | pytest-repeat           | Flaky test detection
Go          | -race flag              | Data races at runtime
Go          | pprof                   | Goroutine profiling
C/C++       | Thread Sanitizer (TSan) | Data races, tsan compile flag
Rust        | -Z sanitizer=thread     | Data races (nightly)

3.2 Go Race Detector

# Run tests with race detector
go test -race ./...

# Run binary with race detector
go run -race main.go

# Build with race detector
go build -race -o myapp
// Example: Go race detector output
// ==================
// WARNING: DATA RACE
// Read at 0x00c00001e0c0 by goroutine 7:
//   main.increment()
//       /app/main.go:12 +0x44
//
// Previous write at 0x00c00001e0c0 by goroutine 6:
//   main.increment()
//       /app/main.go:12 +0x64
// ==================

The report hands you two conflicting accesses to the same address: a read (or write) from one goroutine plus the “previous write” that another one made. The stack traces point at the exact lines involved; fix the access pair they name, not the function that happened to crash. The complete guide to Go concurrency covers the detector’s runtime model in more depth.

3.3 Java Thread Dump Analysis

# Take a thread dump
jstack <pid> > thread_dump.txt

# Detect deadlock
jstack <pid> | grep -A 5 "Found .* deadlock"

# Find waiting threads
jstack <pid> | grep "waiting to lock"

A dump showing two threads “BLOCKED” on each other’s monitors is your deadlock, with the offending locks named right in the output. Take 3 dumps a few seconds apart — threads stuck at the same line across all dumps are your suspects.

3.4 C/C++ with ThreadSanitizer

# Compile with TSan (GCC/Clang)
gcc -fsanitize=thread -g -O1 main.c -o main
clang++ -fsanitize=thread -g -O1 main.cpp -o main

# Run — races are reported to stderr with stack traces
./main

TSan prints reports shaped exactly like Go’s race detector: two unsynchronized accesses to one address with the stacks that produced them. It slows the binary 5-15x, so run it in CI on focused tests rather than on the whole suite.


4. Common Race Condition Patterns

4.1 Check-Then-Act

The one you’ll meet most often in application code: check a condition, then act as though it still holds. Between the check and the act, another thread made it false.

# BAD: check-then-act race
if cache.get(key) is None:  # Thread A checks
    # Thread B also checks here — both see None
    value = expensive_computation(key)
    cache.set(key, value)  # Both threads compute and set

# FIX: use lock or atomic operation
lock = threading.Lock()
def get_or_compute(key):
    with lock:
        if cache.get(key) is None:
            value = expensive_computation(key)
            cache.set(key, value)
        return cache.get(key)

The lock has to wrap both the check and the act. Locking only the set still lets two threads compute the same value. For a catalogue of locking patterns, see the locks and mutexes recipe.

4.2 Lost Update (Read-Modify-Write)

// BAD: lost update
class Counter {
    private int count = 0;
    public void increment() {
        count++;  // Not atomic: read, add 1, write
    }
}

// FIX 1: synchronized
class Counter {
    private int count = 0;
    public synchronized void increment() {
        count++;
    }
}

// FIX 2: AtomicInteger (better performance)
import java.util.concurrent.atomic.AtomicInteger;
class Counter {
    private final AtomicInteger count = new AtomicInteger(0);
    public void increment() {
        count.incrementAndGet();
    }
}

4.3 Lazy Initialization (Double-Checked Locking)

// BAD: broken double-checked locking (Java < 5)
private static Singleton instance;
public static Singleton getInstance() {
    if (instance == null) {                    // Check 1 (no lock)
        synchronized (Singleton.class) {
            if (instance == null) {            // Check 2 (with lock)
                instance = new Singleton();    // Not visible to other threads
            }
        }
    }
    return instance;
}

// FIX: volatile keyword (Java 5+)
private static volatile Singleton instance;
public static Singleton getInstance() {
    if (instance == null) {
        synchronized (Singleton.class) {
            if (instance == null) {
                instance = new Singleton();
            }
        }
    }
    return instance;
}

// BETTER: use holder idiom (no synchronization needed)
private static class Holder {
    static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
    return Holder.INSTANCE;
}

4.4 Non-Atomic Compound Operations

// BAD: non-atomic check-and-set
var balance int
func withdraw(amount int) bool {
    if balance >= amount {        // Check
        balance -= amount         // Act — another goroutine can modify balance here
        return true
    }
    return false
}

// FIX: mutex
var mu sync.Mutex
var balance int
func withdraw(amount int) bool {
    mu.Lock()
    defer mu.Unlock()
    if balance >= amount {
        balance -= amount
        return true
    }
    return false
}

// FIX: atomic compare-and-swap
import "sync/atomic"
var balance int64
func withdraw(amount int64) bool {
    for {
        current := atomic.LoadInt64(&balance)
        if current < amount {
            return false
        }
        if atomic.CompareAndSwapInt64(&balance, current, current-amount) {
            return true
        }
        // Retry if CAS failed (another goroutine modified balance)
    }
}

4.5 Unsafe Publication

A subtler family: the writes happen safely, but other threads see them out of order, or not at all. Classic case: constructing an object in one thread and sharing the reference without synchronization. Another thread can observe a partially built object (fields still at defaults) because the CPU is free to reorder the writes.

// BAD: unsafely published
class Config {
    public int timeout;
    public int retries;
}
Config config;  // shared, not volatile

// Thread 1
config = new Config();
config.timeout = 30;
config.retries = 3;

// Thread 2 may see config != null but timeout == 0
// FIX: publish safely — volatile field, synchronized access,
// or a final field in a properly constructed object
private static volatile Config config;

Rule of thumb: every hand-off of a mutable object between threads needs a “happens-before” edge: a volatile write/read, a lock release/acquire, a thread start/join, or a channel send/receive. No edge, no visibility guarantee.


5. Fixes by Pattern

Each pattern in section 4 maps to a standard fix. The goal isn’t to synchronize everything; it’s to synchronize exactly the accesses that conflict, with the weakest tool that still guarantees correctness. Over-locking is how you trade a race for a deadlock.

5.1 Locks (Mutex)

import threading

class SafeCounter:
    def __init__(self):
        self._value = 0
        self._lock = threading.Lock()

    def increment(self):
        with self._lock:
            self._value += 1

    def get(self):
        with self._lock:
            return self._value

5.2 Atomics

import java.util.concurrent.atomic.*;

// Atomic integer
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();
counter.compareAndSet(0, 1);

// Atomic reference
AtomicReference<String> ref = new AtomicReference<>("initial");
ref.compareAndSet("initial", "updated");

// LongAdder for high-contention counters
LongAdder adder = new LongAdder();
adder.increment();
adder.sum();

5.3 Channels (Go)

// Instead of sharing a variable, communicate through a channel
func counter(incrementCh chan struct{}, resultCh chan int, done chan struct{}) {
    count := 0
    for {
        select {
        case <-incrementCh:
            count++
        case resultCh <- count:
            // Send current count
        case <-done:
            return
        }
    }
}

// Usage
inc := make(chan struct{})
res := make(chan int)
done := make(chan struct{})
go counter(inc, res, done)

inc <- struct{}{}
fmt.Println(<-res) // 1

5.4 Thread-Local Storage

import threading

local_data = threading.local()

def process_request(request):
    local_data.request_id = request.id
    local_data.user = request.user
    # Each thread has its own copy — no race
    handle_request()

5.5 Choosing Between Locks, Atomics, and Channels

The right fix depends on what’s being shared:

SituationBest toolWhy
Counter, flag, single fieldAtomicCheapest correct option; no lock ordering to get wrong
Multi-field invariant (move money A→B)LockThe operation must be atomic as a whole
Passing work between stages (Go)ChannelOwnership moves with the message: nothing to protect
Per-request scratch stateThread-localRemoves the sharing entirely

When in doubt, reach for the weakest tool that’s still correct. Locks are the default because they compose poorly but fail predictably; atomics are faster but only cover one variable; channels redesign the data flow so races can’t form — the CSP channels recipe shows that pattern end to end.


6. Prevention Checklist

Run this list at design time and in review; every race you prevent here is a week of debugging you skip later. For prevention patterns applied to real code, the race condition prevention recipe is the companion piece to this checklist.

Design phase:
  - [ ] Identify all shared mutable state
  - [ ] Prefer immutability where possible
  - [ ] Use thread-safe data structures (ConcurrentHashMap, etc.)
  - [ ] Minimize lock scope — lock only what you need
  - [ ] Define lock ordering to prevent deadlocks
  - [ ] Document thread-safety guarantees of each class

Implementation:
  - [ ] Use language-provided synchronization (not custom spinlocks)
  - [ ] Prefer atomics over locks for single-variable operations
  - [ ] Prefer channels/message-passing over shared memory (Go)
  - [ ] Use final/const/readonly for immutable fields
  - [ ] Avoid lazy initialization unless necessary
  - [ ] Use volatile/atomic for visibility guarantees

Testing:
  - [ ] Run concurrency stress tests in CI
  - [ ] Run with race detector (-race, TSan)
  - [ ] Run tests with high thread count and iterations
  - [ ] Use jcstress for Java memory model verification
  - [ ] Test on multi-core machines (not single-core CI)

Code review:
  - [ ] Check for shared mutable state in new code
  - [ ] Verify lock scope is minimal
  - [ ] Check for nested locks (deadlock risk)
  - [ ] Verify compound operations are atomic
  - [ ] Check for proper error handling inside locks

Code review is your last line of defense. Most races slip in through a diff that looked harmless: a new static field, a cache, a “temporary” shared counter. Anything mutable and reachable from more than one thread deserves a second look.

flowchart diagram: subgraph A[

See Also

Frequently Asked Questions

What is the difference between a race condition and a data race?

A race condition is a logic flaw: the outcome depends on when threads happen to run. A data race is the narrower hardware-level case: two threads hitting the same memory location at once, at least one writing, with no synchronization between them. Every data race is a race condition, though plenty of race conditions never become data races. A check-then-act bug, for example, can race on pure logic even when both accesses are reads.

How do I reproduce a race condition that only happens in production?

Start by collecting as much context as possible from production logs: thread dumps, timestamps, request traces. Then write a stress test that mimics that load and forces the conflicting operations to collide — barriers or countdown latches work well for this. Run it a few thousand times, not once or twice. A race detector (Go -race, TSan for Java/C++) will flag the race even on runs where the output looks fine. If the bug only shows with certain data, replay production snapshots rather than synthetic payloads.

Why does the bug disappear when I add logging?

Because the log line changes the timing; it adds a delay and often a memory barrier, which hides the interleaving that caused the race. That's the signature of a timing bug, not proof the bug is gone. The fix isn't to remove logging but to reproduce the race without perturbing the schedule: stress tests, barriers, and race detectors don't have that problem.

When should I use locks vs atomics vs channels?

Reach for atomics on single-variable operations (counters, flags, simple state); they're faster than locks and can't deadlock. Take a mutex when several fields or a compound action have to move together. In Go, reach for channels when goroutines should hand off work rather than poke shared memory — the data flow becomes explicit in the code. In Go, prefer channels for orchestration and mutex for protecting shared state. In Java, prefer atomics for counters and locks for complex critical sections.

How do I prevent deadlocks when using multiple locks?

Always acquire locks in a consistent global order. If thread A grabs lock1 and then lock2, thread B has to grab them in that same order. Holding one lock while acquiring a second is only safe under that global order. tryLock with a timeout lets you spot and back out of would-be deadlocks. Keep lock scope as small as possible — acquire late, release early. Consider using a single coarse-grained lock if contention is low, and split into fine-grained locks only when profiling shows contention.

What is a memory barrier and why does it matter?

A memory barrier (fence) is a CPU instruction that enforces ordering of memory operations. Without barriers, CPUs and compilers can reorder reads and writes as an optimization, which can break concurrent code. In Java, volatile inserts the barriers that make writes visible to other threads. Go gets them for free through channel operations and the sync primitives. C/C++ leaves it to you: atomic operations or explicit fences. Missing memory barriers cause stale reads and invisible writes — classic race condition symptoms.

Does every race condition corrupt data?

No. Some races only reorder work: two emails sent in the wrong order, a metric counted twice, a duplicate task. Those are still bugs, and they're usually the ones that survive longest because nothing looks "broken" until someone audits the numbers.