Visibility Guarantees of Synchronized Blocks
What you'll learn: How synchronized blocks ensure that changes made by one thread become visible to other threads.
Beyond Mutual Exclusion
You already know that synchronized blocks provide mutual exclusion—only one thread can execute the critical section at a time. But synchronized does something equally important: it guarantees memory visibility across threads.
Without synchronization, changes made by one thread might remain invisible to other threads for an indefinite period. Modern processors use caches, and each thread might see a stale copy of shared data. Synchronized blocks solve this problem.
How It Works
When a thread exits a synchronized block (releases the lock), all changes it made to memory are flushed to main memory. When another thread enters a synchronized block (acquires the same lock), it reads the most recent values from main memory.
Think of it like a bulletin board with strict rules: when you finish posting updates (exit synchronized), you must pin them visibly. When you arrive to read (enter synchronized), you must check the board for the latest postings—you can't rely on old notes in your pocket.
The Happens-Before Relationship
This visibility guarantee creates a happens-before relationship: all actions before releasing a lock are visible to any thread that subsequently acquires that same lock. This applies to all variables accessed by both threads, not just those inside the synchronized block itself.
Why This Matters
Without these visibility guarantees, even perfectly synchronized code could fail. One thread could update a flag variable, but another thread might never see the change and loop forever.
Key Takeaway: Synchronized blocks provide both mutual exclusion and memory visibility guarantees—ensuring that all changes made before releasing a lock become visible to threads that subsequently acquire the same lock.