Card 02/ 09
All 9 cards
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.
| Step | What happens |
|---|---|
| Read | Fetch the current value of count |
| Add | Work out that value plus one |
| Write | Store 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.
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.