liveBook · Manning

Race condition

As explained in Advanced Algorithms and Data Structures

A race condition is a concurrency error in which program behavior depends on the timing or interleaving of operations.

A race condition occurs when concurrent operations produce different results depending on their timing or execution order. An operation may succeed when A finishes before B but fail when B finishes first. section 11.1.2

The error appears when a shared state is checked and changed through separate, non-atomic steps. Two cache updates can both observe available capacity, skip eviction, and insert entries, exceeding the configured limit or overwriting a value. section 7.7

Handle race conditions by coordinating access or by representing work already in progress:

  • Mark a cache miss as loading before computation begins, then let later requests poll for the result or subscribe for notification. section 7.2.4
  • Do not rely on an extra check alone: if the complete set operation remains non-atomic, another operation can still interleave before the update. section 7.7

Two requests add to a nearly full cache

A cache has maxSize−1 entries. Concurrent calls A and B both test the size before either inserts, so both conclude that no eviction is needed. Without synchronization, both add an entry. A synchronized cache serializes the write; a loading marker instead coordinates requests waiting for the same computation. section 7.7

How Advanced Algorithms and Data Structures covers it

How deep it goes
Explains execution order, non-atomic cache updates, loading states, polling, subscriptions, and locking, but does not provide a complete solution.
Examples
Uses concurrent cache insertion, duplicate sentiment requests, and retailer inventory and delivery decisions.
What it assumes
Assumes basic cache operations and contrasts single-threaded assumptions with concurrent execution.
What you can do after
Diagnose interleavings and apply synchronized cache access or in-progress state coordination to reduce inconsistent results and duplicate work.
How it connects
Connects concurrency with synchronization, locks, atomic operations, caching, and publisher-subscriber coordination.

Also explained in

Compare how 20 books explain race condition →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Advanced Algorithms and Data Structures. The section links point to the parts of the book it draws on.