Skip to lesson

Livelock and starvation

Deadlock is not the only way for work to stop. In a livelock, threads stay busy reacting to each other but nothing gets done. In starvation, the program moves on but one thread hardly ever gets its turn.

Livelock: two people stepping aside in a corridor

Livelock is when threads keep reacting to each other and make no progress; starvation is when a thread never gets the resource it needs.

A livelock is when threads are not blocked, they keep running and reacting to each other, yet none of them finishes its work. Think of two people meeting in a hostel corridor.

Example 1 · A livelock in the corridor

CorridorLivelockDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;
public class CorridorLivelockDemo {    static final String[] SIDE = {"left", "right"};    static final int[] side = {0, 0};    static final CyclicBarrier together = new CyclicBarrier(2);    static final List<String> log = new ArrayList<>();    static final int MAX_ROUNDS = 6;
    static void walk(int me) {        try {            for (int round = 1; round <= MAX_ROUNDS; round++) {                together.await();                       // both look at each other                boolean blocked = side[0] == side[1];                if (me == 0) {                    log.add("Round " + round + ": Asha " + SIDE[side[0]] + ", Ravi " + SIDE[side[1]]                            + (blocked ? " -> blocked, both step aside" : " -> they pass"));                }                together.await();                       // both have seen the same picture                if (!blocked) return;                side[me] = 1 - side[me];                // polite rule: always step to the other side            }        } catch (InterruptedException | BrokenBarrierException e) {            Thread.currentThread().interrupt();        }    }
    public static void main(String[] args) throws InterruptedException {        Thread asha = new Thread(() -> walk(0), "asha");        Thread ravi = new Thread(() -> walk(1), "ravi");        asha.start();        ravi.start();        asha.join();        ravi.join();
        for (String line : log) System.out.println(line);        System.out.println("Both were busy every round, yet nobody got past.");    }}
Output
Round 1: Asha left, Ravi left -> blocked, both step aside
Round 2: Asha right, Ravi right -> blocked, both step aside
Round 3: Asha left, Ravi left -> blocked, both step aside
Round 4: Asha right, Ravi right -> blocked, both step aside
Round 5: Asha left, Ravi left -> blocked, both step aside
Round 6: Asha right, Ravi right -> blocked, both step aside
Both were busy every round, yet nobody got past.

What this code does

  • Each round, both threads look at the corridor at the same moment (the first await), then both react (after the second await). Their rule is the same: if blocked, step to the other side. Asha and Ravi both start on the left side of the corridor.
  • Because both follow the same rule at the same time, they mirror each other forever. Both threads are working every round, yet nobody gets past. The demo stops after 6 rounds; a real livelock would not.

Both step aside to the same side, then both step back, again and again.

In code, a livelock usually comes from polite retry logic: "if I cannot get the second lock, release the first and try again at once". If two threads do this in step, they keep failing together. Unlike a deadlock, the threads are RUNNABLE and the CPU is busy, so the app looks alive while it makes no progress.

The corridor examples use a CyclicBarrier so both people react at exactly the same moment. That makes the livelock repeatable; real threads fall in and out of step by chance.

Retry with a random wait to break a livelock

A livelock is broken by making the threads behave differently. The usual way is a random wait before each retry: one thread waits 1 ms, the other 3 ms, and the faster one gets both locks before the slower one comes back.

Example 2 · A random choice breaks the tie

CorridorRandomDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;
public class CorridorRandomDemo {    static final String[] SIDE = {"left", "right"};    static final int[] side = {0, 0};    static final CyclicBarrier together = new CyclicBarrier(2);    static final List<String> log = new ArrayList<>();    static final int MAX_ROUNDS = 6;
    static void walk(int me, Random random) {        try {            for (int round = 1; round <= MAX_ROUNDS; round++) {                together.await();                boolean blocked = side[0] == side[1];                if (me == 0) {                    log.add("Round " + round + ": Asha " + SIDE[side[0]] + ", Ravi " + SIDE[side[1]]                            + (blocked ? " -> blocked" : " -> they pass"));                }                together.await();                if (!blocked) return;                if (random.nextBoolean()) {             // random choice: step aside or wait                    side[me] = 1 - side[me];                }            }        } catch (InterruptedException | BrokenBarrierException e) {            Thread.currentThread().interrupt();        }    }
    public static void main(String[] args) throws InterruptedException {        // fixed seeds only so this output is repeatable; real code uses new Random()        Thread asha = new Thread(() -> walk(0, new Random(7)), "asha");        Thread ravi = new Thread(() -> walk(1, new Random(11)), "ravi");        asha.start();        ravi.start();        asha.join();        ravi.join();
        for (String line : log) System.out.println(line);    }}
Output
Round 1: Asha left, Ravi left -> blocked
Round 2: Asha right, Ravi right -> blocked
Round 3: Asha left, Ravi left -> blocked
Round 4: Asha right, Ravi left -> they pass

What this code does

  • Now each person tosses a coin after a blocked round: step aside or stay. As soon as their choices differ, they pass. Here it took 4 rounds; on average it takes about 3.
  • The seeds 7 and 11 are fixed only so this output never changes. Real code uses new Random() or ThreadLocalRandom.current(), so the timing differs on every run.

Many systems also let the wait grow after each failure, for example 10, 20, 40 ms, with some randomness added. This is called exponential back-off with jitter; payment gateways and network clients retry this way. A fixed rule also works: only one side ever steps aside.

Starvation: unfair locks and long holders

Starvation is when one thread waits again and again while other threads keep getting the resource. The program as a whole makes progress, but that thread does not, or only rarely.

Example 3 · Unfair versus fair lock: who gets the printer

FairLockDemo.javaJava
import java.util.concurrent.locks.ReentrantLock;
public class FairLockDemo {    // three booking counters share one ticket printer, guarded by one lock    static long[] run(boolean fair) throws InterruptedException {        ReentrantLock printer = new ReentrantLock(fair);        long[] tickets = new long[3];        long end = System.nanoTime() + 300_000_000L;      // each test runs for 300 ms        Thread[] counters = new Thread[3];        for (int i = 0; i < 3; i++) {            int me = i;            counters[i] = new Thread(() -> {                while (System.nanoTime() < end) {                    printer.lock();                    try {                        tickets[me]++;                        Thread.sleep(1);                   // printing takes a moment                    } catch (InterruptedException e) {                        return;                    } finally {                        printer.unlock();                    }                }            }, "counter-" + (i + 1));        }        for (Thread t : counters) t.start();        for (Thread t : counters) t.join();        return tickets;    }
    static void print(String label, long[] t) {        long total = t[0] + t[1] + t[2];        System.out.printf("%s: counter-1 %d%%, counter-2 %d%%, counter-3 %d%%%n", label,                t[0] * 100 / total, t[1] * 100 / total, t[2] * 100 / total);    }
    public static void main(String[] args) throws InterruptedException {        print("Unfair lock", run(false));        print("Fair lock  ", run(true));    }}
Sample output
Unfair lock: counter-1 2%, counter-2 24%, counter-3 72%
Fair lock  : counter-1 33%, counter-2 32%, counter-3 33%

What this code does

  • Three booking counters share one ticket printer for 300 ms. With the unfair lock, a counter that has just printed often takes the lock again at once, so one counter may get most turns while another gets almost none. Your percentages will differ on every run.
  • With new ReentrantLock(true) the lock goes to the thread that has waited longest, so each counter gets about a third. The price is fewer tickets in total, because every hand-over has to wake a sleeping thread.

Example 4 · A long holder makes everyone wait

LongHolderDemo.javaJava
import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.concurrent.CountDownLatch;
class ResultBoard {    private Map<String, String> results = new HashMap<>();
    // slow: builds every college's results while holding the lock    synchronized void publishSlow(List<String> colleges, CountDownLatch started)            throws InterruptedException {        started.countDown();        for (String c : colleges) {            Thread.sleep(50);                       // building one college's PDF            results.put(c, "published");        }    }
    // fast: builds outside the lock, then swaps the finished map in one short step    void publishFast(List<String> colleges, CountDownLatch started) throws InterruptedException {        started.countDown();        Map<String, String> fresh = new HashMap<>(results());        for (String c : colleges) {            Thread.sleep(50);            fresh.put(c, "published");        }        synchronized (this) {            results = fresh;        }    }
    synchronized Map<String, String> results() { return new HashMap<>(results); }
    synchronized String lookup(String college) { return results.getOrDefault(college, "not yet"); }}
public class LongHolderDemo {    static void test(String label, boolean slow) throws InterruptedException {        ResultBoard board = new ResultBoard();        List<String> colleges = List.of("COEP", "VJTI", "NIT-T", "IIIT-H");        CountDownLatch started = new CountDownLatch(1);        Thread publisher = new Thread(() -> {            try {                if (slow) board.publishSlow(colleges, started);                else board.publishFast(colleges, started);            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }        }, "publisher");        publisher.start();        started.await();
        long t0 = System.nanoTime();        String answer = board.lookup("COEP");        long waitedMs = (System.nanoTime() - t0) / 1_000_000;        publisher.join();        System.out.println(label + ": student got \"" + answer + "\", waited "                + (waitedMs >= 100 ? "more than 100 ms" : "under 100 ms"));    }
    public static void main(String[] args) throws InterruptedException {        test("Slow publish", true);        test("Fast publish", false);    }}
Output
Slow publish: student got "published", waited more than 100 ms
Fast publish: student got "not yet", waited under 100 ms

What this code does

  • publishSlow holds the board's lock for about 200 ms while it builds four PDFs, so a student's simple lookup waits the whole time. If the publisher ran again and again, students could wait almost forever.
  • publishFast builds the new map with no lock held and swaps it in with one short synchronized step. The student is answered at once with the old data ("not yet") instead of waiting.

The first common cause is an unfair lock. synchronized and new ReentrantLock() make no promise about who goes next, and a thread that has just released a lock often grabs it again before a sleeping waiter wakes up. new ReentrantLock(true) creates a fair lock that serves waiting threads roughly in arrival order, at the cost of lower throughput. The second cause is a long holder: a thread that keeps a lock during slow work, such as building PDFs or calling a server, makes every other thread wait the whole time. The fix is the one from earlier modules: do the slow work outside the lock and keep the locked part short.

Thread priorities do not fix starvation. They are only hints, and their effect depends on the operating system.

Deadlock, livelock and starvation compared

All three are liveness problems: what the code computes may be right, but some work never finishes. They look different from the outside, which helps you tell them apart.

Example 5 · Telling the three apart from the symptoms

DiagnoseDemo.javaJava
record BugReport(String app, boolean anyProgress, boolean cpuBusy, boolean oneThreadNeverServed) {}
public class DiagnoseDemo {    static String diagnose(BugReport r) {        if (r.anyProgress()) {            return r.oneThreadNeverServed() ? "starvation" : "slow, but no liveness bug";        }        // nobody makes progress: are the threads sleeping or spinning?        return r.cpuBusy() ? "livelock" : "deadlock";    }
    public static void main(String[] args) {        BugReport[] reports = {            new BugReport("Bank transfers", false, false, false),            new BugReport("Polite retry loop", false, true, false),            new BugReport("Exam result lookups", true, false, true),            new BugReport("Fest ticket sales", true, true, false)        };        for (BugReport r : reports) {            System.out.println(r.app() + " -> " + diagnose(r));        }    }}
Output
Bank transfers -> deadlock
Polite retry loop -> livelock
Exam result lookups -> starvation
Fest ticket sales -> slow, but no liveness bug

What this code does

  • The first question is whether anything makes progress. If nothing does, a busy CPU points to livelock and an idle CPU to deadlock.
  • If work is getting done but one kind of request is never served, it is starvation. Work that is merely slow for everyone is a speed problem, not a liveness bug.
  • Deadlock: no progress; threads BLOCKED or WAITING; CPU low. Fix: lock ordering, tryLock or one lock.
  • Livelock: no progress; threads RUNNABLE and busy; CPU high. Fix: random back-off or a priority rule.
  • Starvation: the program progresses, but one thread rarely or never gets its turn. Fix: a fair lock or shorter locked sections.
  • In a thread dump, deadlocked threads sit at the same line every time; livelocked threads show up at different lines of the same retry loop.

Next step

Check your understanding

12 quick questions