Card 01/ 09

ConceptDifficulty: Intermediate1 min

Two Threads, One Field, and a Number That Comes Out Wrong

A counter incremented ten million times by each of two threads should read twenty million. It does, twice. The third time it reads 10,238,769, and nothing about the run was different.

java
class Counter {
    int count = 0;
    void increment() { count++; }
}

There is no lock, no synchronisation and no error. Two threads are reading and writing one field, and the result depends on how their instructions happened to interleave — which nothing in the program controls.

This is a race condition: the answer depends on the order two threads happen to run in. The word condition is doing real work in that phrase — the bug is not that something went wrong, but that correctness was conditional on timing all along.

So shared mutable state between threads is the whole problem, and there are exactly two ways it goes wrong. This topic is about telling them apart, because they need different fixes.