Reentrancy and Reentrant Locks
You'll learn what makes a lock "reentrant" and why it prevents a common threading deadlock.
The Core Idea
A reentrant lock (also called a recursive lock) allows the same thread to acquire the lock multiple times without blocking itself. Each time the thread acquires the lock, an internal counter increments; each time it releases, the counter decrements. The lock only becomes fully available to other threads when the counter reaches zero.
Why Reentrancy Matters
Imagine you're holding the key to a room. You enter, lock the door behind you, then realize you need something from a cabinet also locked with the same key. With a non-reentrant lock, you're stuck—you can't give yourself the key you already hold! You'd deadlock yourself.
With a reentrant lock, you can "re-acquire" your own lock. The system recognizes you already own it and lets you proceed, keeping track that you've locked it twice. You must unlock it twice before anyone else can enter.
Common Scenario
Reentrant locks are essential when synchronized methods call other synchronized methods on the same object:
synchronized methodA() {
// holds lock
methodB(); // needs same lock again!
}
synchronized methodB() {
// would deadlock if lock weren't reentrant
}
Without reentrancy, methodA calling methodB would cause the thread to wait for itself to release the lock—instant deadlock.
Thread Ownership
Reentrant locks track which thread owns them. Only the owning thread can re-acquire the lock. Different threads still block as expected, waiting their turn.
Key Takeaway: Reentrant locks allow a thread to safely acquire the same lock multiple times by tracking ownership and acquisition count, preventing self-deadlock in nested synchronized code.