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

Real-World Deadlock: Bank Transfer Example

Analyzing a practical deadlock scenario in concurrent money transfers between accounts.

Real-World Deadlock: Bank Transfer Example

What you'll learn: How deadlock can occur in a realistic banking scenario where two threads simultaneously transfer money between the same pair of accounts.

The Scenario

Imagine a banking system where transfers between accounts require locking both accounts to ensure consistency. Consider two concurrent transfers:

  • Thread A: Transfer $100 from Account 1 to Account 2
  • Thread B: Transfer $50 from Account 2 to Account 1

Each transfer locks the source account first, then the destination account. This seems reasonable, but creates a deadly trap.

The Deadlock Sequence

class Account {
    private int balance;
    
    synchronized void debit(int amount) {
        balance -= amount;
    }
    
    synchronized void credit(int amount) {
        balance += amount;
    }
}

void transfer(Account from, Account to, int amount) {
    synchronized(from) {           // Thread A locks Account1
        synchronized(to) {         // Thread B locks Account2
            from.debit(amount);
            to.credit(amount);
        }
    }
}

The problem: Thread A locks Account1 and waits for Account2, while Thread B locks Account2 and waits for Account1. Neither can proceed—classic circular wait.

Why This Happens

The lock acquisition order depends on runtime arguments. Thread A acquires locks in order (Account1, Account2), while Thread B acquires them in order (Account2, Account1). This violates the deadlock prevention principle of consistent lock ordering.

This real-world example shows why naive synchronization strategies fail in production systems handling bidirectional operations.

Key Takeaway: Bank transfer deadlocks demonstrate how lock ordering based on operation parameters (source/destination accounts) creates circular wait conditions—the solution requires imposing a consistent global ordering independent of operation direction.