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

Recursive Calls in Synchronized Methods

Exploring how recursive synchronized methods work because the lock is reentrant and the same thread can re-enter.

Recursive Calls in Synchronized Methods

What you'll learn: How recursive synchronized methods work seamlessly because the intrinsic lock is reentrant and allows the same thread to re-enter.

The Core Idea

When a synchronized method calls itself recursively, it works without deadlock because Java's intrinsic locks are reentrant. The same thread that already holds the lock can acquire it again (incrementing the internal lock count) and will release it once for each acquisition. This means recursive algorithms can be safely synchronized without the thread blocking itself.

How It Works

Imagine you have a synchronized method that needs to call itself with a smaller problem size (classic recursion). Each recursive call attempts to acquire the same lock—but since the calling thread already owns that lock, Java simply increments the lock's entry counter and lets execution continue. When each method returns, the counter decrements. Only when the counter reaches zero is the lock fully released.

public class RecursiveCounter {
    private int count = 0;

    public synchronized void increment(int n) {
        if (n <= 0) {
            return;  // Base case
        }
        count++;
        System.out.println(Thread.currentThread().getName() + " incremented to " + count);
        increment(n - 1);  // Recursive call - acquires lock again
    }
}

In this example, calling increment(3) causes the thread to acquire the lock three times (once per recursive call). The lock count increments to 3, then decrements back to zero as the stack unwinds. Without reentrancy, the thread would deadlock waiting for itself to release the lock.

Why This Matters

Reentrancy allows you to write naturally recursive synchronized methods without special handling. The lock mechanism tracks how many times the current thread has entered and ensures proper cleanup.

Key Takeaway: Recursive synchronized methods work because intrinsic locks are reentrant—the same thread can acquire the lock multiple times, with the lock fully released only after all recursive calls complete.