If you have ever debugged a production hang at 3 a.m., the first word your team probably reached for was deadlock. It is well documented and a single thread dump usually catches it. But deadlock has quieter siblings that cause just as much pain in production. Often more, because they do not announce themselves with a frozen JVM.
This is a follow-up to the deadlock article. It covers three liveness failures that hide in production code and silently degrade systems: livelock, starvation, and lock convoys. None of them stops your application. Each of them stops it from doing useful work.
Three More Liveness Failures
A liveness property is a guarantee that something good eventually happens. A program is live if every started operation eventually completes. Deadlock breaks this guarantee by having threads block each other forever waiting for locks. Three other failure modes break it just as effectively.
A livelock has threads running but responding to each other in a way that prevents anyone from making progress. Starvation permanently denies a thread the resources it needs while other threads continue to receive them. A lock convoy is a contended lock combined with the OS scheduler creating a feedback loop that crushes throughput, even though the lock itself is held only briefly.
Unlike deadlock, none of these show up as a BLOCKED thread state in jstack. They look like RUNNABLE or WAITING threads spinning, retrying, or simply being passed over. That is what makes them hard.
Livelock
A livelock occurs when threads change state in response to each other but make no overall progress. The processes are not blocked. They are busy doing nothing.
The textbook example is two people meeting in a hallway. Both step left to make way; both step right to correct; both step left again. The threads are running. No work is being done. Translated to Java:
public class PoliteTransfer {
static class Account {
private final String id;
private double balance;
private boolean lockHeld = false;
Account(String id, double balance) {
this.id = id;
this.balance = balance;
}
synchronized boolean tryAcquire() {
if (lockHeld) return false;
lockHeld = true;
return true;
}
synchronized void release() { lockHeld = false; }
}
static void transfer(Account from, Account to, double amount) {
while (true) {
if (from.tryAcquire()) {
if (to.tryAcquire()) {
try {
from.balance -= amount;
to.balance += amount;
return;
} finally {
to.release();
from.release();
}
} else {
// Be polite: release and let the other thread proceed.
from.release();
}
}
// Yield and try again.
Thread.yield();
}
}
}
Two threads transferring funds in opposite directions can grab the first account, find the second one held, release, retry, and start over forever. CPU usage spikes. Thread dumps look healthy. Nothing transfers.
Recognising Livelock in the Wild
Livelock rarely shows up as a literal hallway example. It usually appears as compare-and-swap retries that never succeed because two threads keep invalidating each other’s snapshots. Or as a distributed retry storm: two services failing each other’s calls, both retrying immediately, each retry triggering the other side’s retry. The service is up. The end-to-end request never completes. A third variant is cooperative cancellation gone wrong, where two coroutines or virtual threads each wait for the other to acknowledge cancellation.
The Fix: Randomised Backoff and Resource Ordering
The two reliable cures for livelock are the same cures Ethernet uses for packet collisions. The first is randomised exponential backoff: add jitter so the threads desynchronise. The second is a total ordering of resources. If both transfers always acquire accounts in a fixed order (for example, by id), the symmetric retry pattern disappears. You may now risk deadlock instead, but deadlock is detectable and livelock is not. Pick your poison knowingly.
static void transfer(Account from, Account to, double amount) {
Account first = from.id.compareTo(to.id) < 0 ? from : to;
Account second = first == from ? to : from;
synchronized (first) {
synchronized (second) {
from.balance -= amount;
to.balance += amount;
}
}
}
For the retry-storm variant, libraries such as Resilience4j and Failsafe provide RetryConfig builders with IntervalFunction.ofExponentialRandomBackoff(...). Use them. A constant-interval retry is a livelock waiting to happen.
Starvation
Starvation is a thread perpetually denied the resources it needs to make progress while other threads continue to acquire them. Unlike deadlock and livelock, the system as a whole is making progress. Just not for everyone.
Starvation in Java typically comes from one of four places.
Thread Priorities
Thread.setPriority() is a hint to the OS scheduler. On most operating systems it is a weak hint at best, on some it is ignored entirely. The JVM does not guarantee any priority semantics. A thread set to MIN_PRIORITY may run perfectly fine. A thread set to MAX_PRIORITY may still be preempted. Treat priorities as a coarse suggestion, never as a correctness mechanism. If your code depends on a high-priority thread always winning, your code is wrong on at least one platform you care about.
Non-Fair Locks
By default, synchronized and ReentrantLock are non-fair. Non-fair locks allow barging: when a lock is released, any thread can grab it, including a thread that just arrived. This is good for throughput because it avoids context switches. The downside is that a slow background thread can be starved by a tight loop of fast-arriving threads that always barge ahead.
// Non-fair (default): high throughput, possible starvation.
ReentrantLock lock = new ReentrantLock();
// Fair: FIFO ordering, lower throughput, no starvation.
ReentrantLock fairLock = new ReentrantLock(true);
The fair variant guarantees FIFO ordering, but every acquisition pays for it. In benchmarks the difference can be an order of magnitude. Use fairness only when you can show that starvation is happening and that you cannot redesign the contention away.
Bounded Executors with Unbounded Submitters
A ThreadPoolExecutor with a small core size and a large queue will starve every task at the back of the queue if the front of the queue keeps producing more work. This is common in actor-style code where one actor’s output is another’s input. If the producer outpaces the consumer, the consumer’s downstream tasks never get a thread.
Selectors and Condition Variables
Object.notify() wakes one arbitrary waiter. The JVM has no obligation to wake them in arrival order. Object.notifyAll() wakes all waiters and lets them race for the lock, which is fair but expensive. Condition.signal() has the same semantics as notify() but lives on a Lock, and on a fair ReentrantLock it does pick the longest-waiting thread.
Diagnosing Starvation
Starvation rarely produces a stack trace. The signal you are looking for is a thread whose state is RUNNABLE or WAITING for a long time, while a metric it is responsible for stops moving.
Run jstack -l repeatedly with a few seconds between samples. If the same thread sits in the same WAITING state every time and others move, that thread may be starved. JDK Flight Recorder is more precise: enable the jdk.JavaMonitorWait and jdk.ThreadPark events. Long park durations on a single thread while others succeed are a starvation signature. Application-level metrics also help, especially per-task latency histograms with high p99 or p99.9 values but normal medians.
Lock Convoys
A lock convoy is an interaction between contention and OS scheduling. The mechanism is roughly:
- Many threads need lock L. The lock is held only briefly per thread, so under low contention the system performs well.
- A thread acquires L and is then preempted by the scheduler. Maybe its time slice ended, maybe a page fault occurred.
- While that thread is descheduled, every other thread that needs L blocks. They form a queue.
- When the lock holder is rescheduled and releases L, exactly one waiting thread acquires it.
- That thread also gets preempted before finishing the critical section.
- The queue persists. Throughput collapses to “one critical section per scheduler quantum” instead of “many critical sections per millisecond”.
The lock itself is fine. Each individual acquisition is fast. But the macro behaviour is that the lock holder always seems to be off-CPU, and the queue of waiters never drains.
Where Convoys Hide
Logger lines on a hot path that synchronise on a shared appender. Metrics counters that take a global lock. A shared Random instance instead of ThreadLocalRandom. Singleton caches with synchronised getters. Anywhere small, frequent, shared state is protected by a single lock that hundreds of requests hit per second.
Mitigating Convoys
There is no single fix; the right tool depends on the workload.
Reduce the critical section. Compute everything you can outside the lock. Inside the lock, do only what cannot be done outside.
Replace the lock with a lock-free structure where possible. LongAdder instead of a synchronised counter, ConcurrentHashMap instead of Collections.synchronizedMap, AtomicReference with CAS instead of mutexes for small state.
Use StampedLock for read-heavy workloads. Optimistic reads do not block writers and do not park readers, so the convoy never forms.
import java.util.concurrent.locks.StampedLock;
class Point {
private final StampedLock sl = new StampedLock();
private double x, y;
double distanceFromOrigin() {
long stamp = sl.tryOptimisticRead();
double cx = x, cy = y;
if (!sl.validate(stamp)) { // a write happened
stamp = sl.readLock();
try { cx = x; cy = y; }
finally { sl.unlockRead(stamp); }
}
return Math.sqrt(cx * cx + cy * cy);
}
}
StampedLock is not reentrant and does not support Condition. It is a sharper tool than ReentrantReadWriteLock and you have to use it carefully. For the right workload it eliminates the convoy entirely.
Partition the lock. Instead of one global lock, shard the data and lock per shard. ConcurrentHashMap does this internally; you can do the same for any large keyed structure.
Virtual Threads Change the Picture
Java 21 brought virtual threads to general availability, and Java 26 has continued to refine them. They change the cost model of concurrency in ways that interact with all three failures discussed above.
The good side: starvation from bounded thread pools largely disappears, because virtual threads are cheap. The pattern of “one Spring controller waiting for one platform thread” stops being a constraint. Lock convoys on platform thread pools also matter less because the contention pattern shifts. With one virtual thread per request, you no longer have N platform threads queueing on the same lock from inside a thread pool. You have many virtual threads, but the carrier threads they ride on are scheduled differently.
The bad side: synchronized blocks pin a virtual thread to its carrier in current implementations. If a virtual thread enters a synchronized block and then performs a blocking operation, the carrier cannot service other virtual threads until the synchronized block completes. A small piece of legacy code with synchronized on a hot path can collapse the throughput of an otherwise virtual-thread-friendly system. Replace synchronized with ReentrantLock on any blocking critical section. JDK 24’s JEP 491 reduced this pinning significantly; verify the behaviour for your target version.
Livelock under retry storms is also worse with virtual threads, because the cost of starting another virtual thread is so low that nothing throttles the retry rate. A misconfigured retry policy will happily spin up tens of thousands of virtual threads, all retrying, all failing. Always combine retries with a bulkhead or rate limiter.
A Detection Toolkit
These three failures rarely produce a single smoking gun. The diagnostic playbook is short.
| Symptom | First check | Second check |
|---|---|---|
| App is up, throughput collapsed | jstack repeatedly; look for many BLOCKED threads on the same monitor | async-profiler -e lock to see which lock |
| One thread does no work, others do | jstack -l over time; does the slow thread ever change state? | JFR jdk.ThreadPark events |
| CPU at 100%, no progress | top -H to find hot threads; sample stacks | If retry loops appear: livelock |
| p99 spikes, p50 fine | Trace per-request latency; find the slow request’s stack | Often a convoy on a shared lock |
async-profiler deserves special mention. Its lock profiling mode samples lock contention events from the JVM and produces flame graphs that show which call sites are losing time to contention. It is the single most effective tool for spotting both convoys and starvation patterns in production.
Decisions in Practice
Default to non-fair locks. Reach for new ReentrantLock(true) only when you have measured starvation. Always use exponential backoff with jitter for any retry, in-process or distributed. Order resources before acquiring multiple locks; this is the same rule that prevents deadlock and the symmetric form of livelock. Audit synchronized on virtual-thread paths and replace with ReentrantLock if the critical section can block.
Prefer lock-free structures for counters, accumulators, and simple maps. LongAdder, ConcurrentHashMap, AtomicReference are almost always the right answer for high-contention shared state. For read-heavy state, use StampedLock with optimistic reads. Partition before serialising. Sharding by hash is almost always cheaper than a global lock.
And watch your thread dumps over time, not just once. A single dump cannot distinguish “blocked” from “permanently blocked”.
Conclusion
Deadlock gets the headlines. It is also the easiest of the four classic liveness failures to detect and fix. The harder ones (livelock, starvation, lock convoys) do not announce themselves. They show up as p99 latency spikes, throughput cliffs, and on-call pages where every thread looks healthy and nothing is making progress.
The defensive habits are not exotic. Avoid global locks. Prefer lock-free structures for shared counters and maps. Randomise retry intervals. Audit synchronized blocks on virtual-thread paths. Treat fairness as a deliberate trade-off rather than a default. The diagnostic tools (JFR, async-profiler lock mode, repeated thread dumps) are mature and free.
A correct concurrent program is one in which every thread that should make progress, does. Deadlock-free is necessary. It is not enough.

This article is part of the JAVAPRO magazine issue:
Engineering Decisions
Choose the right technology for the right problem.
Explore practical guidance on modern Java, AI, cloud architectures, APIs, and software design to build maintainable, secure, and future-ready applications.
Discover the edition →