Quick revision
The short answer
A transfer deadlocks when two threads lock the same two accounts in opposite orders. With lock ordering, we always lock the account with the lower id first and the higher id second, so no cycle of waiting can form, which is simple and needs no retries but requires a total order over all locks. With tryLock, we take the first lock, try the second with a timeout, and if that fails release the first, back off with random jitter and retry, which works without a natural order but needs a retry limit and jitter to avoid livelock. In both, every unlock is in a finally block.
What to remember
In this answer, we saw that transfers deadlock when two threads lock the same two accounts in opposite orders, creating a cycle. Lock ordering by account id removes the cycle: it is simple and needs no retries, but every piece of code must follow one total order. tryLock with a timeout releases the first lock when the second is unavailable, so a deadlock cannot persist, but it needs random backoff to avoid livelock, a retry limit and callers that handle failure. In both versions every unlock sits in a finally block.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A transfer deadlocks when two threads lock the same two accounts in opposite orders. With lock ordering, we always lock the account with the lower id first and the higher id second, so no cycle of waiting can form, which is simple and needs no retries but requires a total order over all locks. With tryLock, we take the first lock, try the second with a timeout, and if that fails release the first, back off with random jitter and retry, which works without a natural order but needs a retry limit and jitter to avoid livelock. In both, every unlock is in a finally block.
Why this question is asked
Moving money between two accounts is the standard example of a deadlock because it is so natural: each transfer needs both accounts locked, and transfers go in both directions at once. The same shape appears in any code that locks two resources, such as two rows, two caches or two nodes of a graph. Interviewers ask for working code and the trade-off because both techniques are used in real systems and each fails in its own way. In this answer, we will recap how the deadlock happens, write the lock ordering version, write the tryLock version with backoff, and then compare them.
1A Quick Recap: How the Naive Transfer Deadlocks
Each Account has its own ReentrantLock and a balance. The obvious transfer locks the source, then the destination.
6 messages in order. Play them, or step through them one at a time.
Each thread holds what the other needs.
A deadlock needs four conditions at once: locks are exclusive, a thread holds one lock while waiting for another, locks cannot be taken away, and there is a cycle of threads each waiting for the next. Here thread 1 holds A and waits for B, while thread 2 holds B and waits for A. The cycle is complete and neither can move. Each fix breaks one condition: lock ordering removes the cycle, and tryLock removes the 'hold while waiting forever'.
2Solution 1: Lock Ordering by Account Id
If every thread takes locks in the same global order, a cycle is impossible: a thread holding the lower lock can only wait for a higher one, and no thread holding a higher lock ever waits for a lower one. Account ids give us that order for free.
Notice that the order of locking is decided by id, but the direction of the money is still from and to. We only reorder the locks, never the operation. The same-account check matters because a transfer to oneself would otherwise be a confusing no-op; ReentrantLock is reentrant, so it would not hang, but with a non-reentrant lock it would. If two accounts could ever share an id, we would need a tie-breaker, such as a global lock taken only for that case.
3Solution 2: tryLock With Timeout and Backoff
Sometimes there is no natural order, for example when locks come from different systems or are discovered at runtime. Then we avoid holding a lock while waiting forever. We take the first lock, try to take the second within a short timeout, and if that fails we release the first, so the other thread can finish, wait a short random time, and try again.
Notice why each part is there. Releasing the first lock on failure breaks the 'hold while waiting' condition, so a deadlock cannot persist. The random sleep matters because without it, two threads could fail at the same moment, release, retry at the same moment and fail again, forever: a livelock, where both are busy but neither makes progress. Different random delays break the symmetry. The retry limit stops a thread from looping indefinitely under heavy contention, and returning false lets the caller decide what to do. Every unlock is in a finally block, and unlock is only called on a lock that tryLock actually acquired.
4Comparing the Two Approaches
Lock ordering is simpler. There are no retries, no timeouts to tune, no randomness and no failure result: a transfer always completes, it may just wait. Its weakness is that it needs a total order over all locks that might be taken together, and every piece of code must follow it. In a small class like this, that is easy. In a large system where locks are acquired in different modules, one method that takes them in the wrong order brings the deadlock back.
tryLock with backoff works without any order, and it degrades gracefully: under heavy contention some transfers fail and can be retried later instead of the system hanging. The costs are complexity, the need to pick a timeout and retry limit, the possibility of livelock if the jitter is missing, and a new outcome, 'could not acquire', that callers must handle. Its waits also add latency under contention.
| Aspect | Lock ordering | tryLock with timeout |
|---|---|---|
| deadlock | impossible if everyone follows the order | cannot persist: locks are released |
| needs a total order | yes, such as account id | no |
| retries and timeouts | none | timeout, retry limit, jitter |
| livelock risk | none | yes without random backoff |
| outcome | always completes, may wait | may return false under contention |
| code complexity | low | higher |
5What Real Systems Do
In a database-backed system, the same ideas apply at the row level. Updating rows in a consistent order, for example by primary key, avoids most deadlocks; the database's own deadlock detector aborts one transaction when a cycle forms anyway, which is like tryLock with the database choosing the loser, so the application must retry. In Java code, lock ordering is the usual first choice, with tryLock kept for cases without a natural order or where a bounded wait is a requirement.
6Follow-up questions
What if two accounts can have the same id?
Then the order is not total and the deadlock can come back for that pair. A common fix is a tie-breaker: compare System.identityHashCode, and if that ties too, take a single global tie lock first. With unique ids from a database, this does not arise.
Why not lock both accounts with one global lock?
It is correct and cannot deadlock, but it serialises every transfer in the system, even ones between unrelated accounts. That throws away all parallelism, so it only suits very low volumes.
How would you detect a deadlock that happened anyway?
A thread dump shows it: jstack or jcmd Thread.print reports 'Found one Java-level deadlock' for monitors and ownable synchronizers such as ReentrantLock, listing each thread and the lock it waits for. ThreadMXBean.findDeadlockedThreads() can do the same check from inside the application for monitoring.
7Conclusion
In this answer, we saw that transfers deadlock when two threads lock the same two accounts in opposite orders, creating a cycle. Lock ordering by account id removes the cycle: it is simple and needs no retries, but every piece of code must follow one total order. tryLock with a timeout releases the first lock when the second is unavailable, so a deadlock cannot persist, but it needs random backoff to avoid livelock, a retry limit and callers that handle failure. In both versions every unlock sits in a finally block.
Open with
The deadlock happens when thread 1 transfers from A to B and locks A, while thread 2 transfers from B to A and locks B; then each waits for the other's lock forever.
Then, if they want more
With lock ordering I break the cycle: I compute first and second as the account with the lower id and the one with the higher id, lock first, then second, each unlock in a finally, and inside I still move money from the source to the destination.
Since every thread takes the lower id first, nobody holding a higher lock ever waits for a lower one, so no cycle can form. I also reject transfers to the same account.
The tryLock approach doesn't need an order: I tryLock the source with a timeout, then tryLock the destination with a timeout; if the second fails, the finally releases the first, I sleep a small random time, and retry up to a limit, then return false so the caller can report it.
The trade-off is that ordering is simpler, has no retries, and the transfer always completes, but it needs a total order over all locks and everyone must follow it. tryLock works when there's no natural order and degrades gracefully, but needs a timeout, a retry limit, and random jitter, because without jitter two threads can keep failing in lockstep, which is livelock.
I'd choose ordering by account id here, because the id gives a natural order.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.concurrent, package documentation, JLS chapter 17, Threads and Locks
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a money transfer between two Account objects that cannot deadlock, using either...": https://scrivio-interview-library.netlify.app/java/locks/c8c12bf2cf/