What is livelock, and how is it different from deadlock?
In deadlock, processes are blocked and make no progress. In livelock they keep running and changing state in response to each other, but still make no progress, like two people repeatedly stepping aside in a corridor.
Explain it simply
Two people meet in a narrow corridor. Both step left to let the other pass, then both step right, then left again, forever. They are active, but nobody gets through. That is livelock. In deadlock, both would stand still, each waiting for the other to move first.
- Deadlock: processes are blocked, using no CPU, waiting on each other.
- Livelock: processes are running, burning CPU, but their actions undo or block each other.
Example
A common livelock comes from a "polite" lock strategy:
// both threads run this
while (true):
lock(A)
if (trylock(B) fails):
unlock(A) // back off politely
continue // retry immediately
work()
breakThread 1 locks A then tries B; thread 2 locks B then tries A. Each fails, releases and retries in step. Neither completes.
The usual fix is randomness: wait a random time before retrying, as Ethernet and Wi-Fi do after collisions. Another fix is a global lock order so that no thread needs to back off.
A way to tell them apart in practice: a deadlocked program shows threads blocked on locks and low CPU, while a livelocked one shows high CPU and no useful output.
What to say in the interview
"Both are lack of progress. Deadlocked processes are blocked and idle; livelocked processes keep running and reacting to each other without finishing. Random backoff or a fixed lock order fixes livelock."
Common mistakes
- Saying a livelocked process is waiting. It is actively running.