What Is Reentrancy?
You'll learn: Why Java's intrinsic locks allow the same thread to acquire a lock it already holds—and why this is essential for practical programming.
The Core Idea
Reentrancy means a lock can be acquired multiple times by the same thread that currently holds it. Java's intrinsic locks (monitors) are reentrant by default.
Think of it like a keycard to your office: if you're already inside your office and lock the door, you can still use your keycard to unlock and re-lock it without getting stuck outside. The lock "recognizes" you as the current holder.
Why Reentrancy Matters
Without reentrancy, synchronized code would easily deadlock on itself. Consider this scenario:
public synchronized void outer() {
System.out.println("In outer");
inner(); // Calls another synchronized method
}
public synchronized void inner() {
System.out.println("In inner");
}
When a thread calls outer(), it acquires the object's lock. Inside outer(), it calls inner(), which is also synchronized on the same object.
With reentrancy: The thread already holds the lock, so it proceeds into inner() without blocking. The JVM tracks how many times the thread has acquired the lock and only releases it when the count returns to zero.
Without reentrancy: The thread would wait for itself to release the lock—instant deadlock.
How It Works Internally
Java's monitor maintains an acquisition count and owner thread ID. Each time the owning thread re-enters, the count increments. Each exit decrements it. The lock is only truly released when the count hits zero.
Key Takeaway:
Reentrancy allows a thread to acquire the same lock multiple times, preventing self-deadlock when synchronized methods call other synchronized methods on the same object.