Concurrency in LLD · mid
Deadlock and lock ordering
A deadlock happens when threads hold locks and wait for each other in a cycle. The fix is to always take locks in one global order.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Signature: low CPU, timeouts and no errors. Take a thread dump (jstack or jcmd Thread.print); it shows the cycle directly.
- Example: transfer A to B locks A then waits for B, while transfer B to A locks B then waits for A.
- Fix: always lock in a global order, such as by wallet id with the smaller first, whichever direction the money goes. For three or more wallets sort, then lock.
- Alternatives: tryLock with a timeout and back off; one lock for all transfers if traffic is small; one thread or queue per wallet (actor style).
- Detection: ThreadMXBean.findDeadlockedThreads in a health check, alerts on stuck request threads, timeouts on lock waits.
- In a database two transactions updating rows in opposite order deadlock. The database kills one with a deadlock error, so the app must retry. Update rows in id order.
- Test: run many A to B and B to A transfers at the same time, assert that balances add up and that the test finishes.
The red pen
Common traps: mistake → fix
Mistake: A bigger thread pool fixes it
Fix: more threads just get stuck too.
Mistake: Adding synchronized on the method plus the wallet locks is safe
Fix: other paths can still lock in a different order.
Mistake: Random sleeps avoid it
Fix: they only hide it.
Easy to hard
Questions interviewers ask, easy to hard
- The app freezes when two people pay each other. What happened?
- How do you find a deadlock in a running system?
- How do you prevent it?
- How does it show in a database?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.