Skip to the page

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.

The 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

  1. The app freezes when two people pay each other. What happened?
  2. How do you find a deadlock in a running system?
  3. How do you prevent it?
  4. How does it show in a database?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview