Card 02/ 09

ConceptDifficulty: Intermediate1 min

Why count++ Is Three Steps and Not One

count++ is three characters and looks like one thing happening. It is not, and the gap between those parts is where an update goes missing.

What count++ actually does, in order
StepWhat happens
ReadFetch the current value of count
AddWork out that value plus one
WriteStore the result back into count

Another thread can run between any two of those steps. If both threads read 41 before either writes, both work out 42, and both write 42 — two increments, one gained.

Two threads reading the same value before either writes loses one increment

An operation that cannot be interrupted part-way through is called atomic. count++ is not atomic, and neither is balance = balance - amount, if (map.get(k) == null) map.put(k, v), or anything else that reads a value, computes from it, and writes it back.

So the question to ask of any line touching shared state is how many steps it really is. Reading a field is one step and writing one is one step; everything between them is a gap another thread can get into.