Card 03/ 09
All 9 cards
ConceptDifficulty: Intermediate1 min
The Second Guarantee: Leaving a Lock Publishes What You Wrote
Everyone knows synchronized stops two threads running the same code at once. It does a second thing, and that second thing is what makes it a correctness tool rather than a queueing one.
When a thread leaves a synchronized block, everything it wrote inside is published. When a thread enters a block on the same lock, it sees all of it.
That guarantee covers every field the thread touched, including the ones the block was never about. A lock is therefore a way of publishing a whole set of changes at once, which is something volatile can do for one field and nothing else can do for several.
So the two guarantees travel together and neither is optional. If you lock to write a field, you have to lock to read it too — otherwise you have paid for exclusion and thrown away the visibility.