Course contentsShow
← Java
Lesson 2702 of 2,87049. Synchronization and LockingFree lesson

Livelock in Code: Polite Workers

See a code example where two threads continuously defer to each other, creating livelock without blocking.

Livelock in Code: Polite Workers

You'll learn: How to recognize a livelock scenario in actual Java code where two threads continuously defer to each other without making progress.

The Polite Workers Problem

Imagine two workers trying to pass through a narrow doorway. Each is so polite that when they see the other approaching, they step back to let the other pass. But the other worker does the same thing at the same moment. They repeat this dance endlessly—always moving, but never getting through. That's livelock in code.

Code Example

class PoliteWorker implements Runnable {
    private String name;
    private PoliteWorker other;
    private volatile boolean isActive = true;

    public PoliteWorker(String name) {
        this.name = name;
    }

    public void setOther(PoliteWorker other) {
        this.other = other;
    }

    public boolean isActive() {
        return isActive;
    }

    @Override
    public void run() {
        while (isActive) {
            // Check if other worker is active
            if (other != null && other.isActive()) {
                System.out.println(name + " sees " + other.name + " is busy, stepping back...");
                // Politely defer by briefly pausing
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
                // Still active, will check again
                continue;
            }
            // If we got here, we could proceed, but the loop keeps checking
        }
    }
}

// Usage:
PoliteWorker worker1 = new PoliteWorker("Worker-1");
PoliteWorker worker2 = new PoliteWorker("Worker-2");
worker1.setOther(worker2);
worker2.setOther(worker1);

new Thread(worker1).start();
new Thread(worker2).start();

Both threads continuously see the other as active, defer, and retry—infinitely. They're not blocked (not deadlocked), but they're not progressing either.

Key Takeaway: Livelock occurs when threads remain active but continuously react to each other in ways that prevent progress, often due to overly cautious retry or deferral logic without a mechanism to break the cycle.