Implement a thread-safe money transfer
RevolutSoftware Engineer · Technical ScreenLast updated
This question evaluates a candidate's mastery of concurrent programming and data-integrity principles, focusing on thread safety, atomic state updates, and deadlock avoidance when transferring funds between shared accounts.
Problem: Implement a concurrent-safe transfer function
You are given an in-memory store of bank accounts:
- Each account has an
accountIdand abalance(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
fromIdtotoIdentirely, 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.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.