← Home
🏗Crack System Design with DSA AnimatorSystem DesignNEW
🏗 System Design›Concurrency & Threading

🧯Deadlock / Livelock / Starvation

Different failure modes of concurrent systems � all look like �stuck�, but causes differ.

📌 Key IdeaDeadlock is circular waiting, livelock is active but useless retries, and starvation is unfair progress where some threads never run. Prevent with lock ordering, timeouts/tryLock, fairness, and bounded retries.
🖼

Visual

?? Concurrency failure modes
Deadlock   : A waits B, B waits A (no progress)
Livelock   : Threads keep retrying/yielding (no useful progress)
Starvation : One thread never gets chance due to unfair scheduling/locks
✅

When to Use

  • Designing lock-heavy services and critical sections.
  • Postmortems where requests hang despite low CPU.
  • Interview discussions on correctness under contention.
🚫

When NOT to Use

  • Assuming every hang is deadlock � first inspect thread states.
  • Adding global locks before trying simpler confinement/immutability.
💻

Code Variations

1?? Deadlock via opposite lock orderjava
synchronized (lockA) {
  synchronized (lockB) { /* ... */ }
}
// elsewhere
synchronized (lockB) {
  synchronized (lockA) { /* ... */ }
}
Fix by enforcing one global lock acquisition order.
2?? Deadlock mitigation with tryLock timeoutjava
if (a.tryLock(50, MILLISECONDS)) {
  try {
    if (b.tryLock(50, MILLISECONDS)) {
      try { work(); } finally { b.unlock(); }
    }
  } finally { a.unlock(); }
}
Timeout avoids infinite waiting; add retry/backoff policy.
🔀

Common Confusions Cleared Up

Deadlock vs Livelock

Deadlock threads are blocked waiting. Livelock threads run but keep changing state without completing work.

Deadlock vs Starvation

Deadlock affects a cycle of waiters; starvation can affect one unlucky thread while others continue.

🎤

Interview Q&A

🧾

Quick Cheat Sheet

DeadlockCircular wait � no one moves.
LivelockEveryone moves, nothing completes.
StarvationSome move forever, one never progresses.
Top fixLock ordering + short critical sections.
🔗

Related Topics