Command Palette

Search for a command to run...

PHASE 5Advanced ~6 min· topic 6 of 11

Topic 5.6

Deadlocks

In one line

Thread A holds lock 1 and wants lock 2; thread B holds lock 2 and wants lock 1 — both wait forever.

0/11 · 0%

Think of it like this

Two cars meeting nose-to-nose on a narrow bridge, each waiting for the other to reverse first. Neither will move unless a rule (like 'always give way to the one on the right') breaks the standoff.

Key ideas

  1. 01

    Four conditions (all must hold): mutual exclusion, hold-and-wait, no preemption, circular wait.

  2. 02

    Fix each: no sharing, acquire-at-once, timeout tryLock, global lock order.

  3. 03

    Interviews: spot the cycle in a design (two services locking each other's rows) and prescribe ordering.

  4. 04

    Lock order mantra: sort resource IDs before locking → no cycles possible.

  5. 05

    tryLock(timeout) converts deadlock into a timeout error — better than a hang.

  6. 06

    Distributed deadlock (HLD): two services holding DB rows → same fix, plus saga/compensation.

Java / Spring map

  • →

    ReentrantLock.tryLock(2, SECONDS); consistent ordering via Comparator on resource ids.

Code & diagrams

circular waitdiagram
Rendering diagram…

Explain without notes

01

Why does acquiring resources in sorted-ID order guarantee no circular wait?

Practice

01

Draw the cycle in 'transfer money' between two accounts locked in send-first order and fix the order.

Trade-offs

  • ↔

    Timeouts trade liveness for fake latency spikes; ordering trades flexibility for safety.

Completion checklist

  • I can name the four conditions and show two independent fixes.

Back to phase