A Simple Deadlock Example: Two Locks
You'll learn: How two threads can deadlock by acquiring the same two locks in opposite orders.
The Classic Two-Lock Deadlock Scenario
Now that you understand what deadlock is and its four necessary conditions, let's see the simplest real-world example: two threads competing for two locks in opposite orders.
Imagine two bank accounts, A and B. Thread 1 needs to transfer money from A to B (so it locks A first, then B). Thread 2 simultaneously tries to transfer from B to A (locking B first, then A). If Thread 1 grabs A while Thread 2 grabs B, both are now stuck waiting for the lock the other holds—classic deadlock.
The Code Pattern
class BankAccount {
private int balance;
public BankAccount(int balance) {
this.balance = balance;
}
public int getBalance() { return balance; }
public void withdraw(int amount) { balance -= amount; }
public void deposit(int amount) { balance += amount; }
}
public class DeadlockDemo {
public static void transfer(BankAccount from, BankAccount to, int amount) {
synchronized (from) {
synchronized (to) {
from.withdraw(amount);
to.deposit(amount);
}
}
}
public static void main(String[] args) {
BankAccount accountA = new BankAccount(1000);
BankAccount accountB = new BankAccount(500);
Thread t1 = new Thread(() -> transfer(accountA, accountB, 100));
Thread t2 = new Thread(() -> transfer(accountB, accountA, 50));
t1.start();
t2.start();
}
}
Thread 1 locks A then tries for B. Thread 2 locks B then tries for A. If the timing is unfortunate, both threads freeze forever, each holding one lock and waiting for the other.
Key Takeaway: Deadlock easily occurs when threads acquire multiple locks in inconsistent orders—the nested synchronized blocks create a circular wait dependency that satisfies all four deadlock conditions simultaneously.