Livelock
A livelock is a failure where threads keep running but make no progress. They react to each other forever: yield, retry, back off, collide again. CPU is busy. The work never finishes.
Detailed Explanation
Deadlock is stillness. Livelock is polite motion. Two people in a corridor step aside in the same direction, then the other, forever. In code, two threads use tryLock, fail, unlock what they have, and retry immediately. They stay synchronized in failure. Or a message system keeps bouncing a message because both ends say "you handle it".
The threads are not blocked on a monitor. A thread dump may show them runnable. CPU graphs look healthy. Timeouts fire and the algorithm restarts from scratch. That is why livelock is harder to spot than deadlock.
Causes in Java: naive tryLock loops without jitter, optimistic CAS loops that always conflict on one hot card, and recovery logic that retries the same doomed schedule. Virtual threads that pin carriers can look similar (work is stuck) but that is starvation of carriers, not livelock of the algorithm.
You fix it with randomness or exponential backoff (Thread.sleep with jitter), with a total order so one thread wins, with a queue so work is handed off instead of both sides retrying, or with a lock that blocks instead of spinning. Detect livelock with a progress metric: a counter that must increase. If it does not, fail the operation.
You reach for this diagnosis when a system is hot, not hung, and throughput is near zero. You prevent it by not writing spin loops on contended locks, by bounding retries, and by giving one participant priority.
The cost of a fixed sleep without jitter is that both threads wake together and collide again. The cost of unbounded retry is a livelock that looks like a slow request. Cap retries and return an error.
Code Examples
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class Backoff {
static boolean both(ReentrantLock a, ReentrantLock b) throws InterruptedException {
for (int i = 0; i < 8; i++) {
if (a.tryLock(1, TimeUnit.MILLISECONDS)) {
try {
if (b.tryLock(1, TimeUnit.MILLISECONDS)) {
try {
return true;
} finally {
b.unlock();
}
}
} finally {
a.unlock();
}
}
Thread.sleep(ThreadLocalRandom.current().nextInt(1, 5)); // jitter
}
return false;
}
public static void main(String[] args) throws InterruptedException {
System.out.println(both(new ReentrantLock(), new ReentrantLock())); // prints: true
}
}Common Gotchas
Immediate retry after `tryLock` fails keeps two threads in step
add jitter or block.
High CPU plus no progress is the livelock signature
deadlock is idle CPU.
Bound the retry loop
after N failures, abort and report.