Deadlocks

The four Coffman conditions, resource allocation graphs, prevention, avoidance (Banker's algorithm), detection and recovery, plus livelock and starvation.

Advanced 4 min readLesson 9 of 16 Interview Q&A

A deadlock is a set of threads each waiting for a resource held by another thread in the set, so none of them can ever proceed. The program doesn't crash; it just stops making progress.

T1R1T2R2
T1 waits for R1 (held by T2); T2 waits for R2 (held by T1): a cycle.

The four Coffman conditions

A deadlock can happen only if all four hold at once:

ConditionMeaning
Mutual exclusionA resource can be held by only one thread at a time
Hold and waitA thread holds resources while waiting for more
No preemptionResources can't be forcibly taken away
Circular waitThere's a cycle of threads, each waiting for the next

Break any one and deadlock becomes impossible.

Classic example

// Thread 1: transfer(a, b)    Thread 2: transfer(b, a)
void transfer(Account from, Account to, long amt) {
    synchronized (from) {            // T1 locks a      T2 locks b
        synchronized (to) {          // T1 waits for b  T2 waits for a → deadlock
            from.balance -= amt;
            to.balance += amt;
        }
    }
}

// Fix: lock in a global order (e.g. by id)
void transferSafe(Account from, Account to, long amt) {
    Account first = from.id < to.id ? from : to;
    Account second = from.id < to.id ? to : from;
    synchronized (first) { synchronized (second) {
        from.balance -= amt; to.balance += amt;
    } }
}

Four ways to handle deadlock

1. Prevention — make a condition impossible

BreakTechniqueCost
Mutual exclusionUse shareable resources (read-only data, lock-free structures)Not always possible
Hold and waitAcquire all resources at once, or release everything before requesting moreLow utilisation; must know needs upfront
No preemptionIf a request fails, release what you hold and retry (tryLock with timeout)Can livelock; wasted work
Circular waitGlobal ordering of resourcesDiscipline — the most practical

2. Avoidance — only grant safe requests

The system knows each thread's maximum need and grants a request only if the resulting state is safe: there's some order in which every thread can finish. Banker's algorithm:

  1. Let Available be the free resources and Need = Max − Allocation for each thread.
  2. Find a thread whose Need ≤ Available. Pretend it runs to completion and releases its allocation: Available += Allocation.
  3. Repeat. If every thread can finish, the state is safe; otherwise it's unsafe and the request must wait.

Example with one resource type and 12 units:

ThreadMaxAllocatedNeed
T01055
T1422
T2927

Available = 12 − 9 = 3. T1 can finish (2 ≤ 3) → available 5. T0 can finish (5 ≤ 5) → 10. T2 can finish (7 ≤ 10). Safe sequence: T1, T0, T2.

Elegant, but rarely used in general-purpose OSes: maximum needs are unknown, and the check costs O(m × n²).

3. Detection and recovery

Let deadlocks happen, detect cycles in the wait-for graph periodically or when a request times out, then recover by aborting a victim (or rolling it back). Databases do exactly this: PostgreSQL checks for cycles after deadlock_timeout (1 s by default) and aborts one transaction.

4. Ignore it (the ostrich algorithm)

Most OSes don't handle deadlocks among application locks at all: it's the programmer's job. The rationale is that deadlocks are rare and prevention is expensive.

Livelock and starvation

  • Livelock — threads keep changing state in response to each other but make no progress, like two people stepping aside in a corridor in the same direction over and over. Common with naive "release and retry" schemes. Fix: randomised backoff.
  • Starvation — a thread waits indefinitely because others are always preferred (low priority, unfair locks, writer starvation). Fix: fairness, aging.

Debugging deadlocks in practice

  • Java: jstack <pid> or a thread dump prints "Found one Java-level deadlock" with the cycle.
  • Python: faulthandler.dump_traceback_later, or py-spy dump --pid.
  • Databases: deadlock reports in the logs (SHOW ENGINE INNODB STATUS in MySQL).
  • Use tryLock(timeout) to fail loudly instead of hanging forever.
Key takeaways
  • Deadlock needs mutual exclusion, hold and wait, no preemption, and circular wait.
  • Prevention breaks a condition; lock ordering (breaking circular wait) is the practical fix.
  • Avoidance (Banker's) grants only requests that keep the system in a safe state.
  • Detection finds cycles in the wait-for graph and aborts a victim, as databases do.
  • Livelock = busy but no progress; starvation = indefinite waiting; fix with backoff and fairness.
Interview questions
QWhat are the necessary conditions for deadlock?easy

Mutual exclusion, hold and wait, no preemption, and circular wait (the Coffman conditions). All four must hold simultaneously.

QHow would you prevent deadlocks in a money-transfer service?medium

Always lock accounts in a consistent order (for example ascending account ID), keep transactions short, and use timeouts with retries. In a database, update rows in ID order, and handle deadlock-abort errors by retrying the transaction.