Lesson · Multithreading Fundamentals
Starvation & Fairness: when the lock forgets you
14 min readStarvation & Fairness
Starvation is a thread that is ready to run and never gets its turn, while everyone around it makes progress. The usual cause is a nonfair lock doing exactly what nonfair means: letting arrivals barge past a queue that is never consulted. Fairness fixes it, and fairness is not free.
When the lock forgets you
Starvation is a thread that is ready to run and is repeatedly passed over while other threads complete. It is not blocked the way a deadlocked thread is blocked: it gets scheduled, it loses the race for the lock or the CPU, and it loses every single time.
The difference between the three failure modes is who is moving. In a deadlock nobody moves. In a livelock everybody runs and nobody progresses. Under starvation the system is busy and often useful, apart from one thread that never gets its turn, which is why a starved thread can wait forever while every dashboard looks healthy.
Starvation hides in the aggregate: throughput is fine, and one caller never finishes.
Barging: the default lock is not a queue
ReentrantLock is nonfair by default, and nonfair has a precise meaning: a thread arriving at a free lock can take it immediately, even when other threads are already queued for it. That is called barging, and it is deliberate. The fastest racer wins, instead of a hand-off to a thread that has to be woken up.
The failure mode is equally precise. When arrivals keep coming faster than the queue drains, the head of the queue can be passed over indefinitely. Nothing is broken; nonfair never promised the queued thread the next turn.
synchronized has no fairness option at all. Monitor scheduling is not FIFO and it is not configurable, so who gets in next is whatever the JVM and the operating system decide.
Nonfair locks are fast because they barge, and barging is exactly what starves the queued.
One lock · one queue · two modes
the lock
held: the critical section is long by design
queue · head on the left
new ReentrantLock() is nonfair, which is the default. A long task holds the lock and will release it soon; H1 is about to become the first waiter.
The fairness knobs
Fair mode turns the queue into a queue: on release, the lock or semaphore hands off to the longest-waiting thread instead of accepting whoever arrives first. Most concurrent utilities expose the choice as a constructor argument.
| Building block | Fair mode | Default |
|---|---|---|
| ReentrantLock | new ReentrantLock(true) | nonfair: new ReentrantLock() or (false) |
| Semaphore | new Semaphore(permits, true) | nonfair |
| ArrayBlockingQueue | new ArrayBlockingQueue<>(capacity, true) | nonfair |
| ReentrantReadWriteLock | new ReentrantReadWriteLock(true) | nonfair; readers can starve writers in read-heavy use |
| synchronized | no option exists | monitor scheduling, not FIFO |
| StampedLock | no fairness guarantees | optimistic reads, and it is not reentrant |
Fair mode is a hand-off rule: on release, the lock goes to the longest-waiting thread instead of the fastest arriving one.
Lock queue
Nonfair lets arrivals skip the queue. Fair sends every arrival to the back.Nonfair (the default)
N4 arrives and takes it directly
queue
Every arrival needs one free instant, and H1 is never running at that instant. The lock is working as specified, and the head of the queue can stay there forever.
Fair: new ReentrantLock(true)
N4 arrives and joins the back
served in arrival order, one release at a time
The hand-off wakes exactly the thread whose turn it is, and everyone else keeps queueing. That is the whole trade: an order guarantee, paid for in wake-ups.
Fairness changes the hand-off rule, not the critical section: the same work runs either way, just with the queue respected instead of bypassed.
What fairness costs
A fair hand-off is slower by construction. The releasing thread must wake a specific waiter and then stand down, so the lock spends time in transit that a nonfair lock would spend doing work. That is why nonfair is the default almost everywhere.
The bill arrives as throughput: more context switches, fewer critical sections per second, lower peak numbers under heavy contention. The benefit arrives as tail latency: the oldest waiter is eventually served, so no request waits unboundedly behind a stream of newcomers.
Choose fair mode where a request must eventually get through (latency-sensitive queueing, request-bound locks), and keep the nonfair default where raw throughput is the goal and every caller is equally unimportant.
Fairness costs throughput; starvation costs latency. Pick the currency you can afford.
Priorities and yield are not fairness
Half of the classic starvation causes have nothing to do with lock fairness. They are the CPU, the scheduler hints people reach for, and the shape of the critical section itself.
- Priorities are hints: setPriority accepts 1 to 10, the mapping onto OS scheduling is unspecified, and some platforms ignore it. A low-priority thread can sit unserved while higher-priority work stays runnable, so priorities must never carry correctness or fairness.
- yield() and onSpinWait() are not ordering tools: yield offers the CPU with no guarantee that the offer is taken, and onSpinWait only makes a spin loop friendlier to the hardware. The thread API lesson covers all three of these.
- Long critical sections starve by arithmetic: the longer the lock is held, the fewer turns per second exist to hand out, and a waiter may be waiting on a queue that advances once per long section.
- Oversubscription and spin hogs eat the CPU: far more runnable threads than cores, or a few threads spinning without parking, leave the scheduler no spare capacity for anyone else. Cut the thread count before adding scheduling tricks.
Writer starvation, and how to spot any of it
ReentrantReadWriteLock has a starvation story of its own. In the default nonfair mode a steady stream of readers can keep the lock occupied, and a waiting writer may not get in; fair mode prevents that by queueing the writer, at some cost to read throughput. StampedLock offers optimistic reads and no fairness guarantees of its own.
- A dump shows the queue, not the verdict: a starved thread sits in the same waiting frame across dumps while other threads come and go. That liveness elsewhere is what separates starvation from deadlock.
- Latency tells the story: the tail of one class of request climbs while overall throughput stays flat, because a subset of callers keeps being skipped.
- Contention counters help: ThreadMXBean can report per-thread blocked and waited counts and times, which shows one thread doing the waiting while others hold the lock.
If throughput is fine and one caller never returns, look for a queue that never reaches the front.
What to remember
The order below works because it keeps the investigation cheap: classify first, change a constructor flag second, and only then touch scheduling.
- Ask who is served: starvation means other threads progress and one thread never does.
- Check the lock mode: nonfair is the default, and barging can pass the queue head forever.
- Decide by latency: if the oldest waiter must be served, switch that lock to fair (true), then measure what the throughput costs.
- Do not reach for priorities or yield: they are hints and cannot order a queue.
- If the starvation is CPU-side, cut the number of runnable threads before adding scheduling tricks.
Fairness is a choice you make per lock, not a property of the program: audit the hot locks and pick deliberately.
Fair is not the same as FIFO, and tryLock never queues
A fair ReentrantLock orders lock() calls, and even there the guarantee is a queue with a hand-off rule, not a strict FIFO contract on every path. tryLock() ignores fairness completely: it barges in either mode, so a retry loop built on tryLock can starve a waiter on a perfectly fair lock. When FIFO service is a requirement, use a fair queue (a fair Semaphore, an ArrayBlockingQueue with fair true) or an explicit ordering.
Interview angles
What is starvation?+
A runnable thread that is repeatedly passed over while others progress. It is not blocked and not dead, it just never wins. The classic cause is a nonfair lock combined with a steady stream of arrivals that barge ahead of it.
How does a nonfair lock starve a waiter?+
On release the lock accepts any thread that arrives while it is free: the acquisition path checks the lock state first and the queue later (or not at all in that fast path). Waiters are only consulted when nobody else is competing, which under sustained load can be never.
This is why the fix is the constructor flag and not a retry tweak: the order is decided inside the synchronizer, so the caller cannot vote on it.
What does ReentrantLock(true) buy, and what does it cost?+
Fair mode serves the longest-waiting thread on release, so the queue drains in arrival order and no waiter is skipped. It costs throughput: a hand-off must wake a specific thread and wait for it, work a nonfair lock avoids by letting a running thread barge in.
Does synchronized support fairness?+
No. Monitor acquisition is not FIFO and there is no fairness flag; the JVM and the OS decide who gets the monitor next. If ordering matters, use a java.util.concurrent lock with a fair mode, or a queue.
Common misconception: A common belief is that waiting threads are served in the order they called synchronized. Nothing in the specification promises that.
Do thread priorities help against starvation?+
No. Priorities are hints passed toward the OS scheduler with no portable guarantee, and some platforms ignore them. They are a tuning surface at best and never a correctness or fairness mechanism; fix the contention pattern instead.
A read-heavy ReentrantReadWriteLock starves its writers. What do you do?+
The default nonfair mode lets a stream of readers keep the lock occupied while a writer waits. Fair mode (new ReentrantReadWriteLock(true)) queues the writer so it gets in, at some cost to read throughput. StampedLock is an alternative with optimistic reads, but it offers no fairness guarantees of its own, so measure before switching.