Skip to lesson

Deadlock: conditions, prevention and avoidance

Deadlock is an interviewer favourite because it mixes a definition, a real example, four conditions and a small calculation. They check that you can list all four conditions and say which one each fix breaks.

The four Coffman conditions with a real-life example

Deadlock is a state where every process in a set is waiting for a resource held by another process in the same set, so none of them can ever continue.

The program below plays out two roommates with two locks: Asha holds the extension board and wants the charger, Bhavna holds the charger and wants the board.

Example 1 · Two threads in a circular wait

CircularWaitDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.concurrent.CountDownLatch;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.ReentrantLock;
public class CircularWaitDemo {    static final ReentrantLock board = new ReentrantLock();    // extension board    static final ReentrantLock charger = new ReentrantLock();  // laptop charger    static final CountDownLatch bothHolding = new CountDownLatch(2);    static final List<String> report = Collections.synchronizedList(new ArrayList<>());
    static void roommate(String name, ReentrantLock first, ReentrantLock second, String wanted) {        first.lock();                                  // hold one resource        try {            bothHolding.countDown();            bothHolding.await();            if (second.tryLock(200, TimeUnit.MILLISECONDS)) {                second.unlock();                report.add(name + " got the " + wanted);            } else {                report.add(name + " gave up waiting for the " + wanted);            }        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        } finally {            first.unlock();        }    }
    public static void main(String[] args) throws InterruptedException {        Thread asha = new Thread(() -> roommate("Asha", board, charger, "charger"));        Thread bhavna = new Thread(() -> roommate("Bhavna", charger, board, "board"));        asha.start();        bhavna.start();        asha.join();        bhavna.join();        Collections.sort(report);        report.forEach(System.out::println);    }}
Output
Asha gave up waiting for the charger
Bhavna gave up waiting for the board

What this code does

  • All four conditions hold: locks are exclusive, each thread holds one while waiting for the other, nobody takes a lock away, and the waits form a circle.
  • With plain lock() both threads would wait forever. tryLock with a timeout lets them give up, which breaks the no-preemption condition (each releases what it holds).

A deadlock can happen only if all four Coffman conditions hold at the same time. Remove any one and deadlock becomes impossible, which is the basis of prevention.

  • Mutual exclusion: a resource can be used by only one process at a time (one charger).
  • Hold and wait: a process holds one resource while waiting for another.
  • No preemption: a resource cannot be taken away; it is released only voluntarily.
  • Circular wait: P1 waits for P2, P2 waits for P3, ..., Pn waits for P1.

Revise: Deadlock explained in Java (opens in a new tab)

Order of execution

How the deadlock forms

Put the roommates' story in the order it happens.

Resource allocation graphs

RAG (resource allocation graph) draws processes and resources as nodes, with a request edge from a process to a resource and an assignment edge from a resource to its holder.

The program below stores a wait-for graph, where an edge P1 to P2 means P1 waits for something P2 holds, and uses a depth-first search to find a cycle in two small graphs.

A deadlock cycle with two processes and two resources, one copy of each. R1 is held by P1 and P1 waits for R2. R2 is held by P2 and P2 waits for R1. The edges form a circle, so neither process can ever continue.

Example 2 · Finding a cycle in a wait-for graph

WaitForGraphDemo.javaJava
import java.util.List;import java.util.Map;
public class WaitForGraphDemo {    static boolean hasCycle(Map<String, List<String>> waitsFor, String node,                            Map<String, Integer> state) {        state.put(node, 1);                                    // 1 = on current path        for (String next : waitsFor.getOrDefault(node, List.of())) {            int s = state.getOrDefault(next, 0);            if (s == 1) return true;                           // back to the path: cycle            if (s == 0 && hasCycle(waitsFor, next, state)) return true;        }        state.put(node, 2);                                    // 2 = fully explored        return false;    }
    static boolean deadlocked(Map<String, List<String>> waitsFor) {        Map<String, Integer> state = new java.util.HashMap<>();        for (String p : waitsFor.keySet()) {            if (state.getOrDefault(p, 0) == 0 && hasCycle(waitsFor, p, state)) return true;        }        return false;    }
    public static void main(String[] args) {        Map<String, List<String>> g1 = Map.of(                "P1", List.of("P2"), "P2", List.of("P3"), "P3", List.of());        Map<String, List<String>> g2 = Map.of(                "P1", List.of("P2"), "P2", List.of("P3"), "P3", List.of("P1"));        System.out.println("P1->P2->P3:     deadlock = " + deadlocked(g1));        System.out.println("P1->P2->P3->P1: deadlock = " + deadlocked(g2));    }}
Output
P1->P2->P3:     deadlock = false
P1->P2->P3->P1: deadlock = true

What this code does

  • Each edge means "waits for a resource held by". A depth-first search that returns to a node still on its current path has found a cycle.
  • With single-instance resources, the cycle in the second graph is a deadlock. This is how detection algorithms work, run periodically or when CPU use drops.

A request edge P → R means P is waiting for R; an assignment edge R → P means R is held by P. With single-instance resources the graph can shrink into a wait-for graph with only processes.

If the graph has no cycle, there is no deadlock. With single-instance resources, a cycle means deadlock. With several instances per resource, a cycle means deadlock is possible but not certain, because another holder may release an instance.

Find the bug

Read the graph

Each reading of a graph has one wrong line. Click it.

Single-instance resources. R1 is held by P1, P2 holds R2.

Round 1 of 2

Prevention vs avoidance vs detection and recovery

Deadlock prevention breaks one of the four Coffman conditions by design, so a deadlock can never happen; avoidance instead checks every request at run time.

The program below makes two threads take two locks in one fixed order, so the cycle of waits from the first example can never form.

Example 3 · Prevention: always lock in the same order

LockOrderingDemo.javaJava
import java.util.concurrent.locks.ReentrantLock;
public class LockOrderingDemo {    static final ReentrantLock board = new ReentrantLock();    // resource #1    static final ReentrantLock charger = new ReentrantLock();  // resource #2
    static void useBoth(String name) {        board.lock();            // everyone takes #1 first...        try {            charger.lock();            try {                System.out.println(name + " charged the laptop");            } finally {                charger.unlock();            }        } finally {            board.unlock();        }    }
    public static void main(String[] args) throws InterruptedException {        Thread asha = new Thread(() -> useBoth("Asha"));        asha.start();        asha.join();        Thread bhavna = new Thread(() -> useBoth("Bhavna"));        bhavna.start();        bhavna.join();        System.out.println("No deadlock: both finished");    }}
Output
Asha charged the laptop
Bhavna charged the laptop
No deadlock: both finished

What this code does

  • Numbering resources and always requesting them in increasing order breaks circular wait: nobody can hold #2 while waiting for #1.
  • The joins only make the print order fixed for this page; the ordering rule is what prevents deadlock even when both threads run at the same time.

Prevention breaks one condition by design, avoidance grants a request only if the system stays in a safe state, and detection and recovery lets deadlocks happen, finds them and then kills processes or preempts resources. Many general-purpose OSs mostly ignore deadlock in user programs (the "ostrich" approach) because it is rare and prevention is costly.

  • Break hold and wait: request all resources at once (poor utilisation).
  • Break no preemption: if a request fails, release what you hold and retry.
  • Break circular wait: number all resources and always request in increasing order (the most practical).
  • Mutual exclusion usually cannot be broken: a printer cannot print two jobs at once.

Revise: Fixing a deadlock with lock ordering (opens in a new tab)

Predict the output

Lock ordering

Two transfers use the rule "lock the lower account number first".

A transfer from account 7 to account 3. Which locks does it take, and in what order?

int from = 7, to = 3;
int first = Math.min(from, to), second = Math.max(from, to);
System.out.println("lock " + first + " then " + second);

Banker's algorithm worked example (safe sequence)

Safe state is a state in which some order of the processes, a safe sequence, lets every process get its remaining need, finish and release its resources.

The program below runs Banker's algorithm on the classic data: three resource types, five processes. It checks for a safe sequence, then tests two new requests.

Example 4 · Banker's algorithm: safety check and requests

BankersDemo.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class BankersDemo {    static List<String> safeSequence(int[] available, int[][] alloc, int[][] need) {        int n = alloc.length, m = available.length;        int[] work = available.clone();        boolean[] done = new boolean[n];        List<String> order = new ArrayList<>();        boolean progress = true;        while (progress) {            progress = false;            for (int i = 0; i < n; i++) {                if (done[i]) continue;                boolean fits = true;                for (int j = 0; j < m; j++) if (need[i][j] > work[j]) fits = false;                if (fits) {                    for (int j = 0; j < m; j++) work[j] += alloc[i][j];   // P_i finishes                    done[i] = true;                    order.add("P" + i);                    progress = true;                }            }        }        return order.size() == n ? order : null;    // null = unsafe    }
    static String request(int p, int[] req, int[] available, int[][] alloc, int[][] need) {        for (int j = 0; j < req.length; j++) {            if (req[j] > need[p][j]) return "error: more than declared max";            if (req[j] > available[j]) return "wait: not enough available";        }        int[] av = available.clone();        int[][] al = Arrays.stream(alloc).map(int[]::clone).toArray(int[][]::new);        int[][] nd = Arrays.stream(need).map(int[]::clone).toArray(int[][]::new);        for (int j = 0; j < req.length; j++) {          // pretend to grant            av[j] -= req[j];            al[p][j] += req[j];            nd[p][j] -= req[j];        }        List<String> seq = safeSequence(av, al, nd);        return seq == null ? "deny: state would be unsafe" : "grant, safe sequence " + seq;    }
    public static void main(String[] args) {        int[][] alloc = {{0, 1, 0}, {2, 0, 0}, {3, 0, 2}, {2, 1, 1}, {0, 0, 2}};        int[][] max = {{7, 5, 3}, {3, 2, 2}, {9, 0, 2}, {2, 2, 2}, {4, 3, 3}};        int[] available = {3, 3, 2};        int[][] need = new int[5][3];        for (int i = 0; i < 5; i++)            for (int j = 0; j < 3; j++) need[i][j] = max[i][j] - alloc[i][j];
        for (int i = 0; i < 5; i++) System.out.println("Need P" + i + " = " + Arrays.toString(need[i]));        System.out.println("Safe sequence: " + safeSequence(available, alloc, need));        System.out.println("P1 requests [1, 0, 2]: " + request(1, new int[] {1, 0, 2}, available, alloc, need));        System.out.println("P2 requests [4, 0, 0]: " + request(2, new int[] {4, 0, 0}, available, alloc, need));        System.out.println("P4 requests [3, 3, 0]: " + request(4, new int[] {3, 3, 0}, available, alloc, need));    }}
Output
Need P0 = [7, 4, 3]
Need P1 = [1, 2, 2]
Need P2 = [6, 0, 0]
Need P3 = [0, 1, 1]
Need P4 = [4, 3, 1]
Safe sequence: [P1, P3, P4, P0, P2]
P1 requests [1, 0, 2]: grant, safe sequence [P1, P3, P4, P0, P2]
P2 requests [4, 0, 0]: wait: not enough available
P4 requests [3, 3, 0]: deny: state would be unsafe

What this code does

  • The safety check finds P1 first (Need (1,2,2) ≤ (3,3,2)); after P1 returns its (2,0,0), Available is (5,3,2), which lets P3 and then P4 finish, and so on.
  • Each request is checked against the starting state: P2's request is within its Need but asks for 4 of A when only 3 are free, so it must wait. P4's request fits, but granting it would leave (0,0,2) free, where no process can finish, so it is denied.

Banker's algorithm is the classic avoidance method. Each process declares its Max need in advance. The OS keeps Allocation (what each holds), Available (free instances) and Need = Max − Allocation. The safe sequence for the data above is P1, P3, P4, P0, P2.

  • Compute Need = Max − Allocation for every process.
  • Find a process whose Need ≤ Available (every resource).
  • Pretend it finishes: Available += its Allocation; mark it done.
  • Repeat; if all finish, the state is safe and the order is a safe sequence.
  • For a new request: check Request ≤ Need and ≤ Available, pretend to grant, run the safety check, and grant only if safe.

Trace the code

The safety check, one resource

Watch a safe sequence being found with 10 units in total.

public class SafeCheck {
public static void main(String[] args) {
int[] alloc = {3, 2, 2};
int[] need = {6, 2, 5};
boolean[] done = new boolean[3];
int available = 3;
String order = "";
for (int round = 0; round < 3; round++) {
for (int p = 0; p < 3; p++) {
if (!done[p] && need[p] <= available) {
available += alloc[p];
done[p] = true;
order += "P" + p + " ";
break;
}
}
}
System.out.println(order.trim() + " | available " + available);
}
}

Variables

available
3

Output

(nothing printed yet)

Line 6Three of the 10 units are free at the start.

Step 1 of 12

Deadlock vs starvation

Starvation is when a ready process keeps being passed over and never gets what it needs, although the rest of the system keeps working.

In a deadlock, the processes in the cycle can never proceed without outside help. In starvation a process could proceed but is passed over. The comparison below also shows a third case.

Text
Deadlock:   A waits for B, B waits for A        -> nobody moves, foreverStarvation: C is ready but always passed over  -> others move, C does notLivelock:   A and B keep yielding to each other -> both busy, no progress

A typical starvation case is a low-priority job in priority scheduling. A livelock is the third case: processes keep changing state in response to each other but make no progress, like two people in a corridor who keep stepping aside the same way.

Deadlock implies the involved processes starve, but starvation does not imply deadlock. Revise: Livelock and starvation (opens in a new tab)

Find the bug

Weak spoken answers

Each spoken answer has one wrong sentence. Click it.

Answer to "Deadlock vs starvation?"

Round 1 of 2

Next step

Check your understanding

12 quick questions