Card 01/ 09
Race Conditions: Two Threads, One Field, and a Wrong Number
A counter that reads twenty million twice, and 10,238,769 the third time, from the same code.
A race condition is a bug where a program's result depends on the order in which two threads happen to run. It appears whenever threads share a field that changes, such as a counter, and nothing controls how their reads and writes interleave.
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 that run was different.
class Counter {
int count = 0;
void increment() { count++; }
}There is no lock, no synchronisation and no error. Two threads read and write one field, and the result depends on how their steps happened to interleave, which nothing in the program controls.
The word condition does real work in the name: the bug is not that something went wrong on one run, but that correctness was conditional on timing all along.
Shared state that changes is the whole problem, and it goes wrong in exactly two ways: operations that interleave, and writes that another thread cannot see. They need different fixes, so telling them apart comes first.
← → move through sections and cards