KatInterview

Deadlock-Free Atomic Funds Movement Between Shared Accounts

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencylockingdeadlock

Last updated

Design a concurrent transfer operation over an in-memory account store that never loses updates, is all-or-nothing, preserves total money, and cannot deadlock.

Moving Money Safely Across Threads

An in-memory bank holds a set of accounts. Every account has:

  • an accountId
  • a balance, stored as an integer number of cents

Many threads may call transfer(fromId, toId, amount) at the same time, including calls that touch the same accounts in opposite directions.

What to build

Design the API and implement transfer so that it is:

  • Free of lost updates. Concurrent transfers must never overwrite each other's changes.
  • Atomic. Either the full amount leaves fromId and arrives in toId, or nothing changes at all. No observer may see a debit without its matching credit.
  • Deadlock-free. Transfers between overlapping sets of accounts must always make progress.

Validation rules

  • amount must be greater than zero.
  • Both accounts must exist.
  • If the source account holds less than amount, the transfer fails and nothing changes.
  • After any successful transfer, the sum of all balances is unchanged.

Assumptions

  • A single process (one JVM); no distributed transactions.
  • You may use any in-process primitive: synchronized, ReentrantLock, ReadWriteLock, atomics, concurrent collections, and so on.

What to deliver

Describe your API (including how failures are reported), your implementation, and an argument for why it is correct. Explain specifically how you prevent deadlock, which edge cases you handle, and what alternatives you considered.

Hints

Hint 1

Start with the simplest correct design: one global lock. Then ask what it costs, and how finer-grained locking (one lock per account) could improve throughput.

Hint 2

With two locks per transfer, consider what happens when thread A runs transfer(1, 2) while thread B runs transfer(2, 1). What property of the lock acquisition order would make that situation impossible?

Hint 3

Do the funds check and both balance updates while holding both locks. Also think about what happens when fromId equals toId, and which validations can be done before locking anything.