An online store has one unit left of a popular phone. Two customers press “Buy” within the same few milliseconds. Each request reads the stock, sees 1, decides the purchase can go ahead, and writes stock 0. Both orders are confirmed. The warehouse has one phone and two angry customers. Nobody’s code had an obvious bug; each request, on its own, was correct. The problem was the interleaving, and that is the defining feature of a race condition.
Concurrency and parallelism are not the same
It helps to separate two words that are often used interchangeably. Concurrency is about structure: several tasks are in progress during overlapping periods of time. Parallelism is about execution: several tasks literally run at the same instant on different CPU cores.
A single-core machine can run a concurrent program by switching between threads, but it never runs them in parallel. A Node.js server handles thousands of concurrent requests on one thread. A data-processing job that splits a file across eight cores is parallel.
The distinction matters here because race conditions need only concurrency, not parallelism. Two threads on one core can still interleave badly if the scheduler switches between them at the wrong moment. Two async handlers in Node can race if each awaits a database read and then writes based on what it read, because other handlers run during the await.
The two shapes almost every race takes
Check-then-act. Code checks a condition, then acts on the assumption that it still holds. The stock example is one. So is “if the file does not exist, create it”, “if the username is free, register it” and “if the cache does not contain this key, fetch and store it”. Between the check and the act, another thread can change the world.
Read-modify-write. Code reads a value, computes a new one, and writes it back. Incrementing a counter is the classic case. Even count++, which looks like one operation, compiles to a load, an add and a store. If two threads both load 41, both add 1 and both store 42, one increment is lost. Run two threads that each increment an unsynchronised shared counter a million times, and the final value is typically well short of two million, and different on every run.
Both shapes are fixed the same way in principle: make the check and the action, or the read and the write, a single atomic step that no other thread can interrupt or observe halfway through.
A shared cache that looks harmless
Consider a Java service that caches exchange rates in a static HashMap. When asked for a currency, it checks whether the map contains the key; if not, it calls an external rate API and puts the result in the map; then it returns the map’s value. Many request threads call it at once. Several things can go wrong:
- Duplicate fetches. Ten threads asking for USD at once may all see “not present” and all call the external API. Wasteful, and possibly costly if the API is metered.
- Corrupted structure.
HashMapis not thread-safe. Concurrent puts during a resize can lose entries or leave the internal structure inconsistent. In older Java versions this was known to cause infinite loops during resizing; the implementation changed in Java 8, but concurrent modification is still undefined behaviour you should never rely on. - Visibility. Without synchronisation, the Java memory model does not guarantee that a value written by one thread becomes visible to another in a timely or consistent way.
- Hidden design issues. Nothing ever expires, so rates go stale forever, and the separate check and get could even return null if another thread removed the entry in between.
Switching to ConcurrentHashMap fixes the structural corruption, and its computeIfAbsent method makes “fetch if absent” atomic per key. One caution: the computation runs while part of the map is locked, so a slow network call inside it can block other threads working on nearby keys. For anything involving remote calls and expiry, a purpose-built cache library (Caffeine in Java, for example) handles loading, expiry and concurrent requests for the same key properly.
Tools for making operations atomic
| Tool | Good for | Watch out for |
|---|---|---|
Locks (synchronized, mutexes, ReentrantLock) | Protecting a multi-step section of code | Contention, and deadlock if several locks are taken in different orders |
Atomic variables (AtomicLong, Go’s sync/atomic, C#’s Interlocked) | Counters and single-value updates via compare-and-swap | Only cover one variable at a time |
| Concurrent collections | Shared maps and queues | Individual calls are atomic; sequences of calls are not |
| Database constraints and conditional updates | Races across processes and servers | Must be designed into the schema and queries |
That last row matters for the phone example. In-memory locks only protect one process, and most web applications run several instances. The reliable fix is to push the check into the database write itself: an update that decrements stock only when stock is still at least the requested quantity, and then checks how many rows it changed. If zero rows changed, someone else got there first. A unique constraint does the same job for “is this username free”. Optimistic locking with a version column is another option when the logic is more complex.
Why races survive testing
Races depend on timing, so they appear under load, on machines with more cores, or when a dependency slows down and widens the window between check and act. A test suite running one request at a time will never hit them. Useful counter-measures include race detectors (Go’s -race flag, ThreadSanitizer for C and C++), load tests that deliberately fire concurrent requests at the same resource, and code review that asks one question of every piece of shared state: what happens if two of these run at the same moment?
Written by the RP Strativa Team. Figures and scenarios in the examples are illustrative.
Leave a Reply