medium.com 4 min read Original Source

How Deadlocks Occur in Java (And Smart Strategies to Avoid Them)

👉If you are not a Member — Read for free here :

What Is a Deadlock?

A deadlock occurs when two or more threads are blocked forever, each waiting for a resource that the other thread holds.

Imagine two people trying to pass each other in a narrow hallway. One person says, “You move first.” The other replies, “No, you move first.” Both just stand there, and nobody moves. That’s deadlock.

In programming terms, a resource could be:

  • An object’s lock (synchronized block)
  • A database row/table lock
  • A file handle
  • Or even a network socket

The most common deadlock we see in Java happens with synchronized blocks or methods, when multiple threads lock objects in different orders.

A Simple Example of Deadlock

alice.bow(bob)).start();
new Thread(() -> bob.bow(alice)).start();
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

class Friend {
    private final String name;

public Friend(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public synchronized void bow(Friend friend) {
        System.out.println(this.name + " bows to " + friend.getName());
        friend.bowBack(this);
    }
    public synchronized void bowBack(Friend friend) {
        System.out.println(this.name + " bows back to " + friend.getName());
    }
}
public class DeadlockExample {
    public static void main(String[] args) {
        final Friend alice = new Friend("Alice");
        final Friend bob = new Friend("Bob");
        new Thread(() -> alice.bow(bob)).start();
        new Thread(() -> bob.bow(alice)).start();
    }
}
class Friend {
    private final String name;

public Friend(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public synchronized void bow(Friend friend) {
        System.out.println(this.name + " bows to " + friend.getName());
        friend.bowBack(this);
    }
    public synchronized void bowBack(Friend friend) {
        System.out.println(this.name + " bows back to " + friend.getName());
    }
}
public class DeadlockExample {
    public static void main(String[] args) {
        final Friend alice = new Friend("Alice");
        final Friend bob = new Friend("Bob");
        new Thread(() -> alice.bow(bob)).start();
        new Thread(() -> bob.bow(alice)).start();
    }
}

What happens here?

  1. Alice’s thread enters alice.bow(bob) → acquires lock on Alice.
  2. At the same time, Bob’s thread enters bob.bow(alice) → acquires lock on Bob.
  3. Alice is now waiting to acquire Bob’s lock, but Bob already has it.
  4. Bob is waiting to acquire Alice’s lock, but Alice already has it.

Result? Both threads wait forever. Your program never finishes.

The Four Necessary Conditions for Deadlock

Deadlock doesn’t just happen randomly. It needs four conditions to exist at the same time. These are known as Coffman’s conditions:

  1. Mutual Exclusion
    A resource (like a lock) can only be used by one thread at a time.
  2. Hold and Wait
    A thread holding one resource is waiting to acquire additional resources.
  3. No Preemption
    Resources cannot be forcibly taken away; they must be released voluntarily.
  4. Circular Wait
    A chain of threads exists where each one is waiting for a resource held by the next thread in the chain.

Deadlock occurs only if all four conditions are true. Break even one of them, and you avoid deadlock.

A More Realistic Deadlock Scenario

class Account {
    private int balance;

public Account(int balance) {
        this.balance = balance;
    }
    public int getBalance() {
        return balance;
    }
    public void withdraw(int amount) {
        balance -= amount;
    }
    public void deposit(int amount) {
        balance += amount;
    }
}
class Transfer {
    public static void transferMoney(Account from, Account to, int amount) {
        synchronized (from) {
            synchronized (to) {
                from.withdraw(amount);
                to.deposit(amount);
            }
        }
    }
}
class Account {
    private int balance;

public Account(int balance) {
        this.balance = balance;
    }
    public int getBalance() {
        return balance;
    }
    public void withdraw(int amount) {
        balance -= amount;
    }
    public void deposit(int amount) {
        balance += amount;
    }
}
class Transfer {
    public static void transferMoney(Account from, Account to, int amount) {
        synchronized (from) {
            synchronized (to) {
                from.withdraw(amount);
                to.deposit(amount);
            }
        }
    }
}

Now imagine two threads:

  • Thread1 transfers money from AccountA → AccountB.
  • Thread2 transfers money from AccountB → AccountA.

Both threads will lock one account and wait for the other.
Result: deadlock.

In production, this could freeze your payment service and lock customer money in limbo.

How to Detect Deadlocks

Deadlocks are silent killers. Unlike NullPointerExceptions, they don’t throw errors.

Ways to detect them:

  • Thread Dumps
    Use jstack or tools like VisualVM. If you see threads in BLOCKED state waiting for each other’s locks, that’s a deadlock.
  • Deadlock Detection Tools
    Java has a built-in ThreadMXBean API. Example:

import java.lang.management.*;

public class DeadlockDetector {
    private static final ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
    public static void detectDeadlocks() {
        long[] deadlockedThreads = mbean.findDeadlockedThreads();
        if (deadlockedThreads != null) {
            ThreadInfo[] infos = mbean.getThreadInfo(deadlockedThreads);
            for (ThreadInfo info : infos) {
                System.out.println("Deadlock detected: " + info.getThreadName());
            }
        }
    }
}
import java.lang.management.*;

public class DeadlockDetector {
    private static final ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
    public static void detectDeadlocks() {
        long[] deadlockedThreads = mbean.findDeadlockedThreads();
        if (deadlockedThreads != null) {
            ThreadInfo[] infos = mbean.getThreadInfo(deadlockedThreads);
            for (ThreadInfo info : infos) {
                System.out.println("Deadlock detected: " + info.getThreadName());
            }
        }
    }
}

Strategies to Avoid Deadlocks

Here are several strategies you can use to avoid deadlocks.

1. Lock Ordering

Always acquire locks in a consistent, global order.

class OrderedLocks {
    private final Object lock1 = new Object();
    private final Object lock2 = new Object();

public void safeMethod1() {
        synchronized (lock1) {
            synchronized (lock2) {
                System.out.println("Safe method 1 executed");
            }
        }
    }
    public void safeMethod2() {
        synchronized (lock1) {
            synchronized (lock2) {
                System.out.println("Safe method 2 executed");
            }
        }
    }
}
class OrderedLocks {
    private final Object lock1 = new Object();
    private final Object lock2 = new Object();

public void safeMethod1() {
        synchronized (lock1) {
            synchronized (lock2) {
                System.out.println("Safe method 1 executed");
            }
        }
    }
    public void safeMethod2() {
        synchronized (lock1) {
            synchronized (lock2) {
                System.out.println("Safe method 2 executed");
            }
        }
    }
}

Both methods lock objects in the same order, so no circular wait can occur.

2. Try-Lock with Timeout

Instead of waiting forever, use tryLock() from ReentrantLock.

import java.util.concurrent.locks.*;

class SafeTransfer {
    private final Lock lockA = new ReentrantLock();
    private final Lock lockB = new ReentrantLock();
    public void transfer() {
        try {
            if (lockA.tryLock() && lockB.tryLock()) {
                try {
                    System.out.println("Transfer successful");
                } finally {
                    lockA.unlock();
                    lockB.unlock();
                }
            } else {
                System.out.println("Could not acquire locks, retrying later");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
import java.util.concurrent.locks.*;

class SafeTransfer {
    private final Lock lockA = new ReentrantLock();
    private final Lock lockB = new ReentrantLock();
    public void transfer() {
        try {
            if (lockA.tryLock() && lockB.tryLock()) {
                try {
                    System.out.println("Transfer successful");
                } finally {
                    lockA.unlock();
                    lockB.unlock();
                }
            } else {
                System.out.println("Could not acquire locks, retrying later");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

With tryLock(), if locks aren’t available, the thread can back off and retry later — avoiding deadlock.

3. Deadlock Detection and Recovery

Sometimes, deadlocks can’t be avoided (especially in complex distributed systems). In such cases:

  • Detect the deadlock (using ThreadMXBean)
  • Kill or restart one of the threads holding locks
  • Retry the operation

This approach is common in databases, where deadlock detection and rollback are built-in features.

4. Minimize Locking

The less you lock, the less chance of deadlocks.

Tips:

  • Keep synchronized sections small.
  • Use immutable objects when possible.
  • Prefer concurrent data structures (ConcurrentHashMap, CopyOnWriteArrayList).

5. Use Higher-Level Concurrency Utilities

Instead of manually handling locks, use Java’s concurrency utilities:

  • ExecutorService for managing threads
  • Concurrent Collections
  • Semaphore or CountDownLatch for synchronization

This shifts the complexity from you to well-tested library code.

Best Practices I Follow

Here’s my personal checklist when I write multithreaded code:

  • Always think about lock ordering.
  • Avoid nested locks unless absolutely necessary.
  • Use ReentrantLock with tryLock() if there’s risk of deadlock.
  • Keep critical sections small and simple.
  • Document the locking strategy for the team.
  • Run stress tests with high thread counts to reveal hidden deadlocks.

Java, Deadlock, Multithreading, Concurrency, Java Locks, Synchronized, ReentrantLock, Thread Safety, Programming, Software Engineering

Read my other article :

Senior vs Principal Engineer: Why Their First Answers Sound Like They’re from Different Planets
How two engineers at different levels see the same problem through completely different lenses — and why both…

Thank You for Reading!

✅ “Follow me on Medium to never miss an update!”

If you found this content helpful, feel free to show your support with 👏 claps! 😊 Your encouragement keeps me motivated to share more insights