Video in progress
How do livelock and starvation differ from deadlock? Give an example of each.
In a deadlock, threads wait and stand still. In a livelock they are actively working, changing state by yielding to each other, but they make no progress. In starvation, the system is running, but some threads never get the resource.
📖 Answer
Livelock. Two threads each need two locks and are written to be "polite":
while (true) {
first.lock();
if (second.tryLock()) {
try { doWork(); return; } finally { second.unlock(); first.unlock(); }
}
first.unlock(); // we give way and immediately try again
}
The second thread takes the locks in the opposite order in the same way. With unlucky timing, both keep taking and releasing forever. In a thread dump they are RUNNABLE and CPU is high, which is the difference from a deadlock: jstack doesn't find it on its own.
The fix: a random wait (jitter) before retrying, or a single lock order. Exponential backoff + jitter in network retries is aimed at exactly this problem.
Starvation. Examples:
- a non-fair
ReentrantLockis taken again and again quickly by one thread, and another can't get to the front of the queue; - in a
ReentrantReadWriteLock, a continuous stream of readers makes the writer wait; - in a shared thread pool, long tasks keep pushing short ones back;
- low-priority tasks in a
PriorityBlockingQueuenever reach the front of the queue.
The fixes: a fair lock (slower), separate pools per task type, and "aging" in the queue (priority rises the longer a task waits).
For diagnostics the difference matters: deadlock means low CPU and BLOCKED in the dump; livelock means high CPU and a progress metric of zero; starvation means good average latency, but p99 or some requests are very slow.
Sign up to mark studied questions and save your progress.