Reentrancy Across Multiple Synchronized Blocks
What you'll learn: How a thread holding a lock can seamlessly enter multiple synchronized blocks on the same object without blocking itself.
The Core Idea
You've already seen that Java's intrinsic locks are reentrant—a thread can re-acquire a lock it already holds. This reentrancy doesn't just work within recursive calls; it also applies when a thread encounters multiple synchronized blocks that lock on the same object.
If a thread has already locked object X in one synchronized block, and then during that block's execution it enters another synchronized block that also locks on X, the thread doesn't deadlock or block itself. Instead, the JVM increments the lock's acquisition count and allows the thread to proceed immediately.
How It Works
public class MultiBlockExample {
private final Object lock = new Object();
public void outerOperation() {
synchronized (lock) {
System.out.println("Outer block entered");
// Thread holds lock, count = 1
innerOperation(); // Calls another method with same lock
System.out.println("Outer block exiting");
} // Lock count decremented to 0, lock released
}
public void innerOperation() {
synchronized (lock) {
System.out.println("Inner block entered");
// Thread already holds lock, count = 2
// No blocking occurs!
} // Lock count decremented to 1
}
}
When outerOperation() calls innerOperation(), the thread doesn't wait—it already owns lock. The JVM tracks the entry count (1 → 2 → 1 → 0) and only releases the lock when the count reaches zero.
Why This Matters
Without reentrancy, this pattern would instantly deadlock—the thread would block waiting for a lock it already holds. Reentrancy makes synchronized code composable and natural.
Key Takeaway:
Java's intrinsic locks allow a thread to enter multiple synchronized blocks on the same lock object without blocking itself, making synchronized code modular and preventing self-deadlock.