Skip to the guide

Making a class thread-safe: confinement, immutability and a locking plan

AdvancedConcept6 pages

A class is thread-safe when many threads can call it at once and every rule it promises still holds. You get there by deciding, for each piece of state, whether to keep it to one thread, make it unable to change, or guard it with a lock. The interviewer wants to hear that plan, piece by piece, before you add any code.

A sports club's cash tin

A small sports club keeps its money in a cash tin, with a ledger that lists each payment. The total in the tin and the lines in the ledger must always agree. So the treasurer has one key, and she locks the tin, adds the money, writes the line and unlocks it, all in one go. If the phone rings, she answers it after she has locked up, never in the middle.

Not everything at the club needs that key. The fee sheet on the wall is printed and never changes, so anyone can read it at any time. Each member's own notebook is theirs alone, so it needs no rule at all. A member who wants to see the ledger gets a photocopy, because the original could be torn or written on. The treasurer has also stuck a note on the tin that says how each of these things is looked after.