Reentrancy and Inheritance: Calling super Methods
What you'll learn: How reentrant locks allow synchronized methods in subclasses to safely call their synchronized parent methods without deadlocking.
The Inheritance Challenge
When you override a synchronized method in a subclass, you often need to call the parent's version using super. But what happens when both methods are synchronized and use the same lock (this)? Without reentrancy, you'd have a problem: the thread already holds the lock from the subclass method, and would block trying to acquire it again for the superclass method.
How Reentrancy Solves It
Since Java's intrinsic locks are reentrant, a thread that already owns a lock can acquire it again. When a synchronized method in a subclass calls a synchronized super method:
- The thread enters the subclass's synchronized method (acquires lock, count = 1)
- Calls
super.methodName(), which is also synchronized - The same thread re-acquires the same lock (count = 2)
- Executes the superclass method safely
- Exits superclass method (count = 1)
- Exits subclass method (count = 0, lock released)
The Analogy
Think of it like a building access card. When you enter the main office (subclass method), your card unlocks the door. When you need to access a restricted file room inside (superclass method), the same card works again—you don't need a second card, and you don't get locked out for already using it.
Why This Matters
Without reentrancy, inheritance hierarchies with synchronized methods would be nearly impossible to implement safely. Every super call would risk deadlock, forcing awkward workarounds and breaking object-oriented design principles.
Key Takeaway: Reentrant locks enable synchronized subclass methods to call synchronized superclass methods on the same object without deadlocking, maintaining both thread safety and clean inheritance hierarchies.