Card 03/ 09

ConceptDifficulty: Intermediate1 min

Lock Visibility: Releasing a Lock Publishes Every Write

The second guarantee of synchronized, and why reads need the lock as well as writes.

The synchronized keyword makes two separate guarantees. The familiar one is exclusion: one thread at a time. The second is visibility: when a thread leaves a synchronized block, everything it wrote inside is published, and a thread that then enters a block on the same lock sees all of it. The second is what makes locking a correctness tool rather than a queueing one.

Everything written before a lock is released is visible after the same lock is acquired

The guarantee covers every field the thread wrote, including ones the block was never about. A lock is therefore a way to publish a whole set of changes at once, which volatile, the modifier that publishes each write to a single field, can do for one field and nothing else does for several.

A thread that builds an order, sets its total and marks it ready, all inside one lock, hands another thread a consistent order: the reader, taking the same lock, sees the total and the flag together, never one without the other.

So the two guarantees travel together. If you lock to write a field, you have to lock to read it too; otherwise you have paid for the exclusion and thrown away the visibility.