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

Lock Ordering: The Primary Prevention Strategy

Preventing deadlock by establishing a consistent global order for acquiring multiple locks.

Lock Ordering: The Primary Prevention Strategy

What you'll learn: How to prevent deadlock by always acquiring multiple locks in the same consistent order across all threads.

The Core Idea

Deadlock occurs when threads acquire locks in different orders, creating a circular wait. The most effective prevention strategy is simple but powerful: establish a global ordering for all locks and ensure every thread acquires locks in that exact order.

Think of it like traffic rules at an intersection. If cars from all directions try to enter randomly, gridlock happens. But if everyone follows the same right-of-way rules, traffic flows smoothly.

How Lock Ordering Works

When your code needs multiple locks, define a consistent sequence—perhaps by object ID, creation order, or some natural comparison. Every single code path that needs those locks must request them in that order.

Example scenario: You have two Account objects that need synchronized access during transfers. Instead of locking them in arbitrary order:

// DON'T: Can deadlock
synchronized (fromAccount) {
    synchronized (toAccount) {
        // transfer logic
    }
}

DO: Order locks consistently:

// Establish ordering based on hash code (or ID)
Account first = System.identityHashCode(fromAccount) < System.identityHashCode(toAccount) 
                 ? fromAccount : toAccount;
Account second = first == fromAccount ? toAccount : fromAccount;

synchronized (first) {
    synchronized (second) {
        // transfer logic - now deadlock-free
    }
}

Now, regardless of whether thread A transfers from account X→Y and thread B transfers Y→X, both threads acquire locks in the same order. The circular wait condition is broken.

Why It Works

By eliminating arbitrary lock acquisition orders, you prevent the circular dependency that causes deadlock. One thread will always get both locks first; the other waits cleanly and proceeds when locks are released.

Key Takeaway: Deadlock prevention requires discipline—establish a consistent global lock ordering and follow it religiously in every code path that acquires multiple locks.