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

Practical Example: Reentrant Lock in Action

Walking through a complete example showing reentrancy with nested synchronized method calls and verifying thread safety.

Practical Example: Reentrant Lock in Action

You'll learn: How to observe Java's reentrant locking behavior in a complete, working example with nested synchronized method calls.

The Complete Example

Let's build a class that demonstrates reentrancy through method call chains:

public class BankAccount {
    private double balance = 1000.0;

    // First synchronized method
    public synchronized void withdraw(double amount) {
        System.out.println(Thread.currentThread().getName() + 
                          " acquired lock in withdraw()");
        
        if (hasEnoughBalance(amount)) {  // Nested call to synchronized method
            balance -= amount;
            System.out.println("Withdrew: " + amount + 
                             ", New balance: " + balance);
        } else {
            System.out.println("Insufficient funds");
        }
        
        System.out.println(Thread.currentThread().getName() + 
                          " releasing lock from withdraw()");
    }

    // Second synchronized method - called from within withdraw()
    public synchronized boolean hasEnoughBalance(double amount) {
        System.out.println(Thread.currentThread().getName() + 
                          " entered hasEnoughBalance() - lock already held!");
        return balance >= amount;
    }
}

Running the Example

public class ReentrantDemo {
    public static void main(String[] args) throws InterruptedException {
        BankAccount account = new BankAccount();
        
        Thread t1 = new Thread(() -> account.withdraw(500), "Thread-1");
        t1.start();
        t1.join();
    }
}

What You'll Observe

The output shows the same thread entering two synchronized methods without blocking itself:

Thread-1 acquired lock in withdraw()
Thread-1 entered hasEnoughBalance() - lock already held!
Withdrew: 500, New balance: 500.0
Thread-1 releasing lock from withdraw()

The thread doesn't deadlock when withdraw() calls hasEnoughBalance() because Java's intrinsic locks are reentrant—the same thread can re-acquire its own lock.

Key Takeaway:
Reentrancy allows synchronized methods to call other synchronized methods on the same object safely, preventing self-deadlock and enabling natural object-oriented design patterns.