What is livelock in Java?

Livelock is a concurrency problem in which multiple threads remain active and continuously react to each other's actions, but none of them can complete their intended task. Unlike a deadlock, where threads are blocked and waiting indefinitely, threads in a livelock keep changing their state and consuming CPU resources while making no real progress.

Key Points:

• Threads are not blocked; they remain active and keep executing. • Each thread continuously responds to the actions of other threads. • No useful work is completed despite ongoing activity. • Livelock can lead to high CPU utilization and reduced application performance. • It can be avoided by introducing random delays, retry limits, or improved coordination mechanisms.

Example:

Imagine two people trying to pass each other in a narrow hallway. Both move to the left at the same time, then both move to the right at the same time. They keep reacting to each other politely but never actually pass. This situation is similar to a livelock in Java.

Code Example:

class Worker {

    private boolean active;

    public Worker(boolean active) {
        this.active = active;
    }

    public synchronized void work(Worker other) {
        while (active) {

            if (other.active) {
                System.out.println(Thread.currentThread().getName()
                        + " gives way to other worker.");
                continue;
            }

            System.out.println(Thread.currentThread().getName()
                    + " is working.");
            active = false;
        }
    }
}

Interview Tip:

A concise interview answer is: "Livelock occurs when two or more threads continuously respond to each other's actions and keep changing state without completing their work. Unlike deadlock, threads remain active and consume resources, but no actual progress is made."