Lock Acquisition and Release Semantics
What you'll learn: You'll understand the memory visibility guarantees that Java provides when a thread enters and exits a synchronized block or method.
The Happens-Before Relationship
When you use synchronized, Java doesn't just prevent multiple threads from executing the same block simultaneously—it also establishes happens-before relationships that control memory visibility.
Here's what happens:
- On lock acquisition (entering synchronized): The thread sees all changes made by the previous holder of that lock
- On lock release (exiting synchronized): All changes made while holding the lock become visible to future lock holders
Think of it like a relay race: when Runner A hands off the baton (releases the lock) to Runner B (who acquires it), Runner B not only gets the baton but also "sees" everything Runner A did during their leg of the race.
Why This Matters
Without these semantics, even with a lock preventing simultaneous access, threads might see stale cached values. The happens-before guarantee ensures that:
private int sharedValue = 0;
synchronized void update() {
sharedValue = 42; // Write happens
// Lock release happens-before next acquisition
}
synchronized void read() {
// Lock acquisition sees all previous writes
System.out.println(sharedValue); // Guaranteed to see 42 if run after update()
}
The lock release from update() happens-before the lock acquisition in read(), so read() is guaranteed to see sharedValue = 42.
Beyond the Synchronized Block
This guarantee extends to all writes made during the synchronized block, not just to fields directly touched. Every variable modification becomes visible to the next lock holder.
Key Takeaway: Lock acquisition and release create happens-before relationships that guarantee memory visibility—when you acquire a lock, you see all changes made by the previous holder; when you release it, your changes become visible to future holders.