Course contentsShow
← Java
Lesson 2673 of 2,87049. Synchronization and LockingFree lesson

Reentrant Method Calls: Same Thread, Same Lock

Seeing how a synchronized method can call another synchronized method on the same object without deadlocking.

Reentrant Method Calls: Same Thread, Same Lock

You'll learn how synchronized methods can safely call other synchronized methods on the same object without causing deadlock.

The Core Idea

When a thread holds a lock on an object and calls another synchronized method on that same object, the thread doesn't block waiting for itself. Instead, Java recognizes the thread already owns the lock and simply increments an internal counter. This is reentrancy in action—the same thread can "re-enter" the lock it already holds.

This behavior is crucial for real-world code. Imagine a synchronized method that validates input, then calls another synchronized method to update state. Without reentrancy, the thread would deadlock trying to acquire a lock it already owns!

How It Works

public class Account {
    private int balance = 0;

    public synchronized void deposit(int amount) {
        balance += amount;
        logTransaction(amount); // Calls another synchronized method
    }

    public synchronized void logTransaction(int amount) {
        System.out.println("Deposited: " + amount);
        System.out.println("New balance: " + getBalance()); // Another!
    }

    public synchronized int getBalance() {
        return balance;
    }
}

When a thread calls deposit(), it acquires the lock on the Account object. The same thread then calls logTransaction() and getBalance()—both synchronized—without issue. Java tracks the lock depth internally, releasing the lock only when the outermost synchronized method completes.

Think of it like a keycard: You swipe once to enter a building (acquire lock), and that same card opens every door inside (reentrant calls). You don't need to swipe again until you leave the building (release lock).

Key Takeaway: Intrinsic locks in Java allow a thread to re-acquire the same lock multiple times through nested synchronized method calls, preventing self-deadlock and enabling natural method composition.