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

Nested Synchronized Blocks and Lock Ordering

Learn how to safely nest synchronized blocks and why consistent lock ordering prevents deadlock.

Nested Synchronized Blocks and Lock Ordering

You'll learn how nesting synchronized blocks requires consistent lock acquisition order to prevent deadlock.

What Are Nested Synchronized Blocks?

When one synchronized block appears inside another, you're nesting synchronization. This happens when a thread already holding one lock needs to acquire a second lock to complete its work.

synchronized(lockA) {
    // Thread holds lockA
    synchronized(lockB) {
        // Thread now holds both lockA and lockB
        // Critical section using both resources
    }
    // Released lockB, still holds lockA
}
// Released lockA

This is perfectly legal—a thread can hold multiple locks simultaneously.

The Deadlock Danger

The problem arises when different threads acquire the same locks in different orders:

Thread 1:

synchronized(lockA) {
    synchronized(lockB) {
        // work
    }
}

Thread 2:

synchronized(lockB) {  // Opposite order!
    synchronized(lockA) {
        // work
    }
}

Now imagine: Thread 1 locks A and waits for B, while Thread 2 locks B and waits for A. Neither can proceed—classic deadlock.

The Solution: Consistent Lock Ordering

Always acquire locks in the same global order across all threads. If your application has locks A, B, and C, every thread must acquire them in that exact sequence (e.g., always A→B→C, never B→A).

Think of it like a one-way street system: everyone follows the same direction, preventing head-on collisions.

// Both threads use A-then-B ordering
synchronized(lockA) {
    synchronized(lockB) {
        // Safe: consistent ordering prevents deadlock
    }
}

Key Takeaway: When nesting synchronized blocks, always acquire locks in a consistent, well-defined order across all threads to prevent deadlock. Document your locking protocol clearly.