Problem: Implement a concurrent-safe transfer function
You are given an in-memory store of bank accounts:
-
Each account has an
accountId
and a
balance
(integer cents).
-
Multiple threads may call
transfer(fromId, toId, amount)
concurrently.
Task
Implement transfer(fromId, toId, amount) such that it is:
-
Correct under concurrency
(no lost updates).
-
Atomic
: either the money moves from
fromId
to
toId
entirely, or nothing changes.
-
Deadlock-free
under concurrent transfers between overlapping accounts.
Rules
-
Validate inputs:
-
amount > 0
-
accounts must exist
-
reject/return failure on insufficient funds
-
The total sum of money across all accounts must remain unchanged after any successful transfer.
Assumptions
-
Single process / single JVM (no distributed transactions).
-
You may use locks (e.g., synchronized/ReentrantLock/ReadWriteLock) or other concurrency primitives.
Deliverable
Provide the API design and implementation approach, including how you prevent deadlocks and ensure correctness.