Deadlock-Free Atomic Funds Movement Between Shared Accounts
Data Structure DesignModel answerLast 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
fromIdand arrives intoId, 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
amountmust 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Give each account its own lock. A transfer acquires the locks of both accounts it touches, checks the balance, applies the debit and credit, and releases the locks. To prevent deadlock, the two locks are always acquired in a fixed global order: ascending accountId, regardless of which account is the source.
API design
TransferResult transfer(long fromId, long toId, long amountCents)
Return an explicit result code rather than a bare boolean, so callers and logs know why a transfer failed:
OKINVALID_AMOUNTSAME_ACCOUNTACCOUNT_NOT_FOUNDINSUFFICIENT_FUNDS
Money is stored as long cents (never double; use BigDecimal only if fractional rules matter).
The registry is a ConcurrentHashMap<Long, Account>, or a plain map built once and then only read. Each Account holds id, balance, and its own ReentrantLock. Account locks protect balances; the map only protects membership.
Why the naive version deadlocks
If transfers lock from first and then to, thread A running transfer(1, 2) holds lock 1 and waits for lock 2, while thread B running transfer(2, 1) holds lock 2 and waits for lock 1. Neither can proceed.
The fix: global lock ordering
Always lock the account with the smaller id first. Deadlock requires a cycle of threads, each holding a lock and waiting for one held by the next. With ordered acquisition, each wait goes from a lower id to a strictly higher id, so following the cycle would need ids to increase forever and return to the start, which is impossible. Direction of the transfer no longer matters.
Implementation (Java)
public TransferResult transfer(long fromId, long toId, long amount) {
if (amount <= 0) return TransferResult.INVALID_AMOUNT;
if (fromId == toId) return TransferResult.SAME_ACCOUNT;
Account src = accounts.get(fromId);
Account dst = accounts.get(toId);
if (src == null || dst == null) return TransferResult.ACCOUNT_NOT_FOUND;
Account first = fromId < toId ? src : dst;
Account second = fromId < toId ? dst : src;
first.lock.lock();
try {
second.lock.lock();
try {
if (src.balance < amount) return TransferResult.INSUFFICIENT_FUNDS;
src.balance -= amount;
dst.balance += amount;
return TransferResult.OK;
} finally {
second.lock.unlock();
}
} finally {
first.lock.unlock();
}
}
Why it is correct
- No lost updates. Every read-modify-write of a balance happens under that account's lock, so transfers touching the same account are serialized.
- Atomicity. The funds check and both writes sit in one critical section holding both locks. No thread can observe the debit without the credit, and no other withdrawal can slip between the check and the debit (no time-of-check/time-of-use gap). All validation happens before any mutation, so a failed transfer writes nothing.
- Conservation. A success applies
-amountand+amount; a failure applies nothing. The total is invariant. - Deadlock freedom. Ordered acquisition, as argued above, and release in
finallyso exceptions cannot leak locks. - Self-transfer. Reject it (or treat it as a no-op success, which is also defensible). Otherwise a non-reentrant lock would be taken twice and the thread would block on itself. Even with a reentrant lock, the explicit rule keeps behavior unambiguous.
Complexity
- Time: O(1) work per transfer (two lookups, two lock acquisitions). Waiting time under contention depends on how hot the accounts are.
- Space: O(N) for N accounts, one lock each; O(1) extra per transfer.
Transfers on disjoint account pairs run fully in parallel.
Edge cases
amount <= 0(or non-integral input in a dynamically typed language): reject before locking.- Unknown account id: reject before locking.
- Balance exactly equal to
amount: allowed, leaving zero. - Opposite-direction storms on the same pair: safe, because order is by id.
- Exceptions in the critical section:
finallyreleases locks. - Overflow: with
longcents, useMath.addExactif balances could approach the limit. - Accounts added at runtime: use a concurrent map; consider how account removal interacts with in-flight transfers (for example, mark closed under the account lock).
Consistent reads
A totalBalance() audit or any multi-account snapshot must lock every involved account in the same ascending-id order. Reading balances without locks can return a total that is temporarily off, because a transfer may be half-visible.
Alternatives and trade-offs
- Single global lock. Trivially correct and deadlock-free, but serializes every transfer. A fine baseline, poor throughput.
- Striped locks (hash id to one of K locks). Bounded memory, still needs ordered acquisition by stripe index, and two accounts may share a stripe (handle by locking once).
tryLockwith timeout and retry. Avoids deadlock without ordering, but risks livelock and needs backoff; ordering is simpler and deterministic.- Optimistic approach (versioned balances plus CAS). Works for single-account updates, but a two-account update needs multi-word atomicity, so it becomes complex. Not worth it here.
- Single-threaded actor or partitioned executor. Route all operations on an account to one thread. Cross-partition transfers then need coordination, which reintroduces the same ordering problem.
- Ids that are not comparable. Order by
System.identityHashCode, and on a tie take a global tie-breaker lock first.
Common mistakes
- Checking the balance before taking locks, then debiting after (TOCTOU).
- Locking in
from,toorder, which deadlocks on opposite-direction transfers. - Forgetting the self-transfer case.
- Holding locks while doing slow work such as I/O or logging.
- Using
doublefor money. - Releasing locks outside
finally.
Testing
Create 100 accounts, run 32 threads each performing many random transfers in both directions, join them, then assert that the total equals the initial total and no balance is negative. A hang indicates deadlock; a wrong total indicates a race. Add a targeted test with two threads repeatedly doing transfer(1,2) and transfer(2,1).