Concurrency and Race Conditions
What goes wrong when several tasks touch the same data at once, and why the result depends on timing.
What is it?
Concurrency means several tasks are in progress during the same period; they may take turns on one core. Parallelism means tasks literally execute at the same instant on different cores. Concurrency is about structure, parallelism is about execution. A single-core machine can be concurrent but not parallel.
Concurrency becomes hard when tasks share mutable state. A race condition is a bug where the result depends on the exact timing or interleaving of operations. It might work a million times and fail on the million-and-first, which makes races some of the hardest bugs to find.
Three ideas explain most races:
- Atomicity. An operation is atomic if no other task can observe it half done. count += 1 looks like one step but is really read, add, write. - Check-then-act. "If the file doesn't exist, create it" fails when another task acts between your check and your action. - Memory visibility. On modern CPUs and compilers, a write made by one thread isn't guaranteed to be seen by another thread promptly, or in the same order, unless you use synchronization.
Explain like I'm 10
Two people share a bank account with $100. Both check the balance at the same moment, see $100, and each withdraws $80. Each check was correct when it happened, but by the time they acted the world had changed. The bank now has -$60.
Examples
Lost updates: count += 1 is not atomic (Java)
public class Counter {
private int count = 0;
public void increment() {
count++; // read, add 1, write back: three steps
}
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Runnable work = () -> { for (int i = 0; i < 100_000; i++) counter.increment(); };
Thread first = new Thread(work), second = new Thread(work);
first.start(); second.start();
first.join(); second.join();
System.out.println(counter.count); // usually less than 200000
}
}Fixing it: atomic increment or a lock
import java.util.concurrent.atomic.AtomicInteger;
private final AtomicInteger count = new AtomicInteger();
public void increment() { count.incrementAndGet(); } // single atomic operation
// or
private int lockedCount = 0;
public synchronized void incrementLocked() { lockedCount++; } // one thread at a timeCheck-then-act race (Python)
import os
# Racy: another process can create the file between the check and the open
if not os.path.exists("report.lock"):
open("report.lock", "w").close()
# Atomic: the OS checks and creates in one step, failing if it already exists
try:
os.close(os.open("report.lock", os.O_CREAT | os.O_EXCL))
except FileExistsError:
print("Someone else holds the lock")The fix is to let one atomic operation do both the check and the act. Databases do the same with unique constraints, INSERT ... ON CONFLICT, or conditional updates.
How it works
Interleaving. The scheduler can pause a thread between any two machine instructions. For count++ on two threads:
The bad interleaving is: thread A reads 5, thread B reads 5, A writes 6, B writes 6. Two increments, one effect. This is a lost update.
Data race vs race condition. A data race is a specific low-level bug: two threads access the same memory location, at least one writes, and there's no synchronization between them. In C, C++ and Go that's undefined or unspecified behavior. A race condition is the broader logic bug where timing changes the outcome; it can happen even with no data race (for example, two atomic operations used in a check-then-act sequence).
Memory visibility and reordering. CPUs keep values in per-core caches and store buffers, and both compilers and CPUs reorder instructions when a single thread can't tell the difference. Another thread can tell. Without a synchronization point, thread B may never see thread A's write to a done flag, or may see the flag before the data it was supposed to guard.
Happens-before. Language memory models (Java, C++, Go) define which writes are guaranteed visible to which reads. Releasing a lock happens-before the next acquire of the same lock; a write to a Java volatile or a C++ atomic happens-before a read that sees it. If you use these tools correctly, you get sequentially consistent behavior for your program.
Ways to avoid races: don't share (each thread owns its data), share only immutable data, pass messages (channels, queues, actors), or protect shared mutable state with locks or atomics.
Time Thread A Thread B count
---- -------- -------- -----
1 read count (5) 5
2 read count (5) 5
3 add 1 -> 6 5
4 add 1 -> 6 5
5 write 6 6
6 write 6 6 <- one update lost
Concurrency (1 core): A A B B A B A (interleaved)
Parallelism (2 cores): A A A A A A A
B B B B B B B (simultaneous)Why does it exist?
Concurrency lets programs use multiple cores and stay responsive while waiting on slow I/O. As soon as concurrent tasks share mutable data, though, the programmer has to reason about every possible interleaving, and hardware optimizations like caches and reordering make the real set of possibilities larger than intuition suggests. Race conditions are the price; synchronization and memory models are the tools for paying it.
When to use it
Think about races whenever two or more of these share mutable data: - threads in one process (thread pools, parallel loops, web request handlers), - async tasks that interleave at await points, - processes or services touching the same file, database row or cache key.
Reach for immutable data or message passing first, atomics for single counters and flags, and locks for invariants spanning several fields.
When not to use it
- Don't introduce concurrency for work that's fast enough sequentially; the correctness cost is real. - Don't protect data that isn't shared. Thread-local or request-local data needs no synchronization. - Don't use volatile or atomics as a general substitute for locks; they make single operations safe, not multi-step invariants.
Common mistakes
Assuming
x++,x += 1orlist.appendin a check-then-act sequence is atomic because it's one line of source code.Testing concurrent code a few times, seeing it pass, and concluding it's correct. Races may appear only under load or on different hardware.
Thinking single-threaded async code (Node.js, asyncio) can't race. Any
awaitbetween a read and a write lets other tasks run in between.Using a plain boolean flag to signal another thread without
volatile/atomic/locking, so the other thread may never see the change.Making each method thread-safe but calling two of them in sequence (
if (!map.containsKey(k)) map.put(k, v)) and assuming the combination is safe.
Practice exercises
- Easy:
Run the lost-update counter with 2, 4 and 8 threads and record the final counts. Then fix it with an atomic counter and confirm the result is always correct.
- Medium:
Write an async Python or JavaScript function that reads a balance, awaits a short sleep, and writes balance - amount. Run two withdrawals concurrently and show the race, then fix it with an
asyncio.Lockor by removing the await between read and write. - Hard:
Write a Go program with an intentional data race on a shared map or counter, run it with
go run -race, and interpret the report. Then fix it once with a mutex and once by confining the data to a single goroutine that receives updates over a channel.
Interview questions
What is the difference between concurrency and parallelism?
Concurrency is structuring a program as multiple tasks whose execution overlaps in time, possibly by interleaving on one core. Parallelism is running multiple computations at literally the same instant on multiple cores. Concurrency is about dealing with many things; parallelism is about doing many things at once.
What is a race condition?
A bug where the program's correctness depends on the relative timing of operations in concurrent tasks. Examples are lost updates on a shared counter and check-then-act sequences where state changes between the check and the act.
What is the difference between a data race and a race condition?
A data race is unsynchronized concurrent access to the same memory location where at least one access is a write; it's a memory-model violation and undefined behavior in C/C++. A race condition is a higher-level logic error about ordering. You can have a race condition with no data race, such as two individually atomic calls used in a non-atomic sequence.
Why isn't `count++` thread-safe?
It's a read-modify-write: load, add, store. Two threads can both load the same value and both store value+1, losing an update. Use an atomic increment or a lock.
What is a check-then-act race, and how do you fix it?
Checking a condition and then acting on it in separate steps, so another task can change the condition in between (lazy initialization, 'create if not exists', double-booking). Fix by making check and act a single atomic operation: a lock around both, compare-and-swap, putIfAbsent, O_EXCL, or a database unique constraint or conditional update.
What is a memory visibility problem?
One thread's write isn't seen by another thread, or is seen in a different order, because of CPU caches, store buffers, and compiler or CPU reordering. Without a happens-before relationship (locks, volatile, atomics, channel operations), the reader has no guarantee of seeing the write.
Can single-threaded JavaScript have race conditions?
Yes. There are no data races because only one callback runs at a time, but logical races happen whenever an async operation spans an await: two requests read the same state, both await, and both write based on stale values. The same applies to responses arriving out of order.
What strategies avoid race conditions without locks?
Don't share state (confinement to one thread), share only immutable data, use message passing (channels, actors, queues), use atomic operations and CAS, or push atomicity into the database with transactions and constraints.
How would you find a race condition that only shows up in production?
Use race detectors (Go -race, ThreadSanitizer) in CI and load tests, add logging with timestamps and thread IDs around the suspect state, write stress tests that run the code many times with random delays, and review code for shared mutable state accessed without synchronization. Look for check-then-act and read-modify-write patterns.
What does 'happens-before' mean in a memory model?
It's a partial ordering guaranteeing that if action A happens-before action B, B sees A's effects. It's established by program order within a thread and by synchronization between threads: unlock before lock of the same mutex, a volatile/atomic write before a read that observes it, a channel send before the matching receive, thread start and join.