Concurrent Bank Account Transfer

Hard
ConcurrencyMutexDeadlockLock OrderingAtomic OperationsTransaction

Problem Statement

Design a thread-safe bank account system that supports concurrent deposits, withdrawals, and transfers between accounts. The key challenge is implementing transfer(from, to, amount) without deadlock, race conditions, or lost updates.

class BankAccount {
    private final int id;
    private long balance;
    public BankAccount(int id, long initialBalance) {}
    public void deposit(long amount) {}
    public boolean withdraw(long amount) {} // Returns false if insufficient funds
    public long getBalance() {}
    public int getId() {}
}

class Bank {
    public Bank() {}
    public void addAccount(BankAccount account) {}
    // Thread-safe transfer — must be atomic (no partial state)
    public boolean transfer(int fromId, int toId, long amount) {}
    public long totalBalance() {} // Sum must remain constant (conservation law)
}

Key Entities

  • BankAccount: Individual account with balance and a per-account ReentrantLock.
  • Bank: Manages multiple accounts; coordinates cross-account operations.
  • Lock ordering: To prevent deadlock in transfer(), always acquire locks in account-ID order.

Requirements

  1. Deposit and withdraw must be atomic per account.
  2. Transfer must be atomic across both accounts — no partial state (either both debit+credit happen or neither).
  3. Deadlock-free for concurrent transfers between any pair of accounts.
  4. totalBalance() must always return the same sum (money conservation).
  5. Insufficient funds must be handled gracefully.

Asked at: Amazon, Google, Morgan Stanley, Goldman Sachs, Visa, PayPal, Paytm, Razorpay

!Constraints

- Account IDs are unique positive integers. - Balances are non-negative longs. - Up to 1000 concurrent transfer operations. - Circular transfers (A→B→C→A concurrently) must not deadlock. - totalBalance() must return correct sum even during concurrent transfers.
Output

Run or submit your code to see output here.