{}DSA Atlas

Deadlocks, Livelocks & Starvation

The four Coffman conditions, resource-allocation graphs, prevention, avoidance with the Banker's algorithm (fully worked), detection and recovery, plus livelock, starvation, priority inversion and database deadlocks.

Intermediate7 interview questions

What is a deadlock?

A set of threads is deadlocked when each is waiting for an event (usually the release of a resource) that only another thread in the set can cause. Nobody can proceed — forever.

Python
import threading, time

a, b = threading.Lock(), threading.Lock()

def t1():
    with a:
        time.sleep(0.1)
        with b:            # waits for t2 to release b
            print("t1 done")

def t2():
    with b:
        time.sleep(0.1)
        with a:            # waits for t1 to release a
            print("t2 done")

threading.Thread(target=t1).start()
threading.Thread(target=t2).start()   # → hangs forever

The four Coffman conditions

All four must hold at once:

ConditionMeaningHow to break it
Mutual exclusionresource can't be sharedmake it shareable (read-only data, lock-free structures) — often impossible
Hold and waithold one, wait for anotherrequest all resources at once; or release everything before requesting more
No preemptioncan't take a resource awayallow preemption: try-lock with timeout, roll back and retry
Circular waitcycle of waitsimpose a global order on resource acquisition

Resource-allocation graphs

Draw threads as circles and resources as boxes. A request edge T → R means T is waiting for R; an assignment edge R → T means T holds R.

T1 T2 Lock A Lock B held by held by T1 waits for B T2 waits for A Cycle: T1 → B → T2 → A → T1 Single instance of each resource: a cycle ⇔ deadlock. Multiple instances per resource type: a cycle means deadlock is possible, not certain.
Red edges are requests (waiting); grey edges are assignments (holding).

With single-instance resources this collapses to a wait-for graph (T1 → T2 if T1 waits for something T2 holds); a cycle means deadlock.

Strategy 1: Prevention

Lock ordering (breaks circular wait)

The most practical technique. Give every lock a rank and always acquire in increasing rank.

def transfer(src, dst, amount):
    first, second = sorted([src, dst], key=lambda acct: acct.id)   # global order
    with first.lock:
        with second.lock:
            src.balance -= amount
            dst.balance += amount
void transfer(Account from, Account to, long amount) {
    Account first = from.id < to.id ? from : to;
    Account second = from.id < to.id ? to : from;
    synchronized (first) {
        synchronized (second) {
            from.balance -= amount;
            to.balance += amount;
        }
    }
}

Try-lock and back off (breaks no-preemption / hold-and-wait)

Java
while (true) {
    if (a.tryLock(50, TimeUnit.MILLISECONDS)) {
        try {
            if (b.tryLock(50, TimeUnit.MILLISECONDS)) {
                try { doWork(); return; } finally { b.unlock(); }
            }
        } finally { a.unlock(); }
    }
    Thread.sleep(ThreadLocalRandom.current().nextInt(10));   // random backoff avoids livelock
}

Strategy 2: Avoidance — the Banker's algorithm

Each process declares its maximum need upfront. Before granting any request, the system checks that it would remain in a safe state.

Worked example

Three resource types with totals A = 10, B = 5, C = 7:

ProcessAllocation (A B C)Max (A B C)Need = Max − Alloc
P00 1 07 5 37 4 3
P12 0 03 2 21 2 2
P23 0 29 0 26 0 0
P32 1 12 2 20 1 1
P40 0 24 3 34 3 1

Available = total − sum of allocations = (10 − 7, 5 − 2, 7 − 5) = (3, 3, 2).

Safety check — repeatedly pick a process whose Need ≤ Work:

StepPickNeed ≤ Work?Work after it finishes (Work + Allocation)
start(3, 3, 2)
1P1(1,2,2) ≤ (3,3,2) ✓(5, 3, 2)
2P3(0,1,1) ≤ (5,3,2) ✓(7, 4, 3)
3P4(4,3,1) ≤ (7,4,3) ✓(7, 4, 5)
4P0(7,4,3) ≤ (7,4,5) ✓(7, 5, 5)
5P2(6,0,0) ≤ (7,5,5) ✓(10, 5, 7)

All finish → safe, with safe sequence ⟨P1, P3, P4, P0, P2⟩.

Request 1: P1 asks for (1, 0, 2). Request ≤ Need(1,2,2) ✓ and ≤ Available(3,3,2) ✓. Pretend to grant: Available = (2,3,0), P1's Allocation = (3,0,2), Need = (0,2,0). The safety check succeeds (P1, P3, P4, P0, P2) → grant.

Request 2 (afterwards): P4 asks for (3, 3, 0). Available is (2,3,0); 3 > 2 → resources not available → P4 waits.

Request 3 (afterwards): P0 asks for (0, 2, 0). Pretend: Available = (2,1,0). Now no process's Need fits (P1 needs B=2, P3 needs C=1, P4 and P2 need A ≥ 4) → unsafe → deny, P0 waits, even though the resources are physically available.

Python
def is_safe(available, allocation, need):
    work = available[:]
    finish = [False] * len(allocation)
    order = []
    progressed = True
    while progressed:
        progressed = False
        for i, done in enumerate(finish):
            if not done and all(n <= w for n, w in zip(need[i], work)):
                work = [w + a for w, a in zip(work, allocation[i])]
                finish[i] = True
                order.append(i)
                progressed = True
    return all(finish), order

def request(pid, req, available, allocation, need):
    if any(r > n for r, n in zip(req, need[pid])):
        raise ValueError("process exceeded its declared maximum")
    if any(r > a for r, a in zip(req, available)):
        return False                                   # must wait: not available
    avail2 = [a - r for a, r in zip(available, req)]
    alloc2 = [row[:] for row in allocation]; need2 = [row[:] for row in need]
    alloc2[pid] = [a + r for a, r in zip(alloc2[pid], req)]
    need2[pid] = [n - r for n, r in zip(need2[pid], req)]
    safe, _ = is_safe(avail2, alloc2, need2)
    return safe                                        # grant only if still safe

Banker's is rarely used in general-purpose OSes (max needs aren't known, processes come and go), but it's a favourite exam/interview question and its idea — only admit work you can guarantee to finish — reappears in admission control and resource quotas.

Strategy 3: Detection and recovery

Let deadlocks happen, then find and break them.

  • Detection: build the wait-for graph and look for cycles (DFS, O(V + E)). With multi-instance resources, run a Banker's-like detection algorithm using current requests instead of max needs.
  • When to run: on every wait (cheap with small graphs), periodically, or when CPU utilisation drops suspiciously.
  • Recovery:
    • abort one or all deadlocked processes (choose the victim by priority, work done, resources held, rollbacks so far — avoid starving the same victim);
    • preempt resources and roll back the victim to a checkpoint (databases roll back the transaction).

Strategy 4: Ignore it

Linux, Windows and macOS don't prevent deadlocks between user threads — it's the application's responsibility. The kernel itself uses lock ordering and the lockdep validator to catch violations in testing.

ProblemThreads blocked?Progress?Fix
Deadlockyes, forevernoneordering, timeouts, detection
Livelockno, busynonerandomised backoff, tie-breakers
Starvationone thread waits indefinitelyothers progressaging, fair locks/queues
Priority inversionhigh-prio waits on low-priomedium-prio runspriority inheritance / ceiling

Priority inversion

HML L locks R H H blocked waiting for R… M runs (doesn't need R) — preempts L L unlocks H finally runs With priority inheritance, L runs at H's priority while holding R, so M cannot preempt it.
The medium-priority task indirectly blocks the high-priority task.

Deadlocks in databases and distributed systems

  • Databases: row/table locks form cycles; the engine detects the cycle, aborts a victim, and the application must retry. Reduce by locking rows in a consistent order (ORDER BY id … FOR UPDATE), short transactions, and good indexes.
  • Distributed locks: a holder that crashes or pauses (GC) can hold a lock "forever" — use leases with TTLs and fencing tokens (see Backend concurrency).
  • Thread pools: a task that waits for another task submitted to the same bounded pool can deadlock when all workers are waiting (thread-starvation deadlock). Use separate pools or non-blocking composition.
  • Microservices: synchronous call cycles (A → B → A) with bounded worker pools can deadlock under load; avoid cycles and always set timeouts.

Interview questions

0 / 7 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.