Livelock vs Deadlock in Java
Fast recall
Quick revision
Core answer
Distinguishing between the two types of stuck conditions — deadlock versus livelock
Confusing livelock with deadlock or not having a concrete example of livelock
Give the classic polite people in a hallway analogy and explain why livelock is harder to detect in production
Interview-ready guide
Interview answer
Deadlock means threads cannot continue because they are waiting in a cycle. A simple case is Thread A holding lock 1 while waiting for lock 2, and Thread B holding lock 2 while waiting for lock 1. Livelock means the threads are still taking actions—such as releasing and retrying—but their responses keep colliding, so no request completes.
I would not diagnose the difference from CPU usage or one thread state alone. A monitor deadlock may show BLOCKED, while locks built on parking may show WAITING; a livelock can spin at high CPU or sleep between retries. I would use a thread dump plus progress metrics. Consistent lock ordering prevents the usual deadlock cycle. Randomized or bounded backoff can break a livelock by stopping both participants from repeating the same timing.
Livelock vs Deadlock in Java
Direct Answer
In deadlock, threads cannot progress because they wait in a dependency cycle. In livelock, threads keep changing state or retrying in response to one another but still complete no useful work. Livelock often consumes CPU, but CPU level and Java thread state are symptoms, not definitions.
Code Example
public class LivelockDemo {
static volatile boolean aYields = true;
static volatile boolean bYields = true;
public static void main(String[] args) {
// Each thread keeps stepping aside for the other -> active, but no progress
Runnable a = () -> {
while (bYields) { Thread.onSpinWait(); } // busy-waiting, not blocked
System.out.println("A proceeds");
};
Runnable b = () -> {
while (aYields) { Thread.onSpinWait(); }
System.out.println("B proceeds");
};
new Thread(a).start();
new Thread(b).start();
}
}
In deadlock both threads sit idle in BLOCKED. In livelock both run flat out yet neither finishes — fix it by breaking symmetry with randomized backoff or lock ordering.
Common Mistakes & Pitfalls
- Using the terms interchangeably: calling every stuck condition "deadlock" misses that livelock is a distinct problem with different symptoms.
- Not knowing the hallway analogy: it is the standard explanation interviewers expect — not having it ready looks unprepared.
- Forgetting CPU usage: the key differentiator is that livelock burns CPU while deadlock does not — leaving this out misses the practical impact.
Check your understanding
Answer these without looking back at the article.
- How do you detect livelock in a Java application?
- What is starvation and how does it differ from deadlock?
- How does randomized backoff prevent livelock?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.