AlgoViz

Correctness: races on shared state

hard 75 min

When several threads use the same data, their steps mix, and a rule that each of them respects can still break.

Watch lesson5:01

Where it shows up

The same pattern appears across everyday software.

  • Java ConcurrentHashMap

    Its documentation says the entire `computeIfAbsent` call is performed atomically. This is the compound step that `containsKey` and `put` do not give you.

  • Java LongAdder

    Documented as giving significantly higher throughput than `AtomicLong` under high contention, at the expense of more space. One value, spread over cells.

  • SimpleDateFormat and DateTimeFormatter

    The old class is documented as not synchronized, with the advice to create one per thread. The newer one is documented as immutable and thread-safe. The fix was to remove the change.

  • CopyOnWriteArrayList

    Iterators work on a snapshot of the array, so no synchronization is needed while traversing. Each change copies the array.

  • Linux RCU

    The kernel documentation explains that a removal replaces references while readers run: each reader sees the old or the new version. Reclaiming the old one waits until readers are done.

  • Redis INCR

    The command reads, adds and writes as one atomic operation on the server, and its page shows how a get followed by a check can go wrong.

  • Django F expressions

    The documentation shows how letting the database do `field + 1` avoids the race of reading into Python and saving back.

  • Clang Thread Safety Analysis

    `GUARDED_BY(mu)` on a field lets the compiler warn when it is used without that mutex. The rule table from the Verify page, checked on each build.

  • Rust Mutex

    The data lives inside `Mutex<T>`, and you reach it only through `lock()`. Forgetting the lock does not compile.

  • Go race detector

    Introduced with Go 1.1. Programs built with `-race` report unsynchronized accesses that happened in that run.