Quick revision
The short answer
The non-fair lock favours throughput: under heavy contention, threads arriving at the right moment keep barging in, and a few unlucky threads lose again and again, which shows up as multi-second tail latency. Fair mode stops that starvation, so p99 improves, but every hand-off now wakes a parked thread while the lock sits idle, so throughput drops. The deeper problem is that the lock is too contended, so I would measure hold times and waiters with JFR or async-profiler, shorten the critical section, split the lock or remove the shared state, and only then decide on fairness against the latency and throughput goals.
What to remember
In this answer, we saw that the long tail comes from a heavily contended non-fair lock, where barging lets most threads in quickly while a few lose repeatedly, and that fair mode shares the waiting evenly but adds a context switch to every hand-off, costing about 40 percent of throughput. Both point to the real problem, contention, so we measure hold times and waiters with JFR or async-profiler, shorten the critical section, split the lock or remove the shared state, and only then choose a fairness mode based on the service's latency and throughput goals.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The non-fair lock favours throughput: under heavy contention, threads arriving at the right moment keep barging in, and a few unlucky threads lose again and again, which shows up as multi-second tail latency. Fair mode stops that starvation, so p99 improves, but every hand-off now wakes a parked thread while the lock sits idle, so throughput drops. The deeper problem is that the lock is too contended, so I would measure hold times and waiters with JFR or async-profiler, shorten the critical section, split the lock or remove the shared state, and only then decide on fairness against the latency and throughput goals.
Why this question is asked
This scenario is common in real services: a lock that was fine at lower load becomes the bottleneck, and the first fix someone tries is the fairness flag, because the symptom looks like unfairness. The flag does change the symptom, which makes it look like the answer, but it trades one problem for another. Interviewers want to see us reason from the numbers to the mechanism and then to the root cause. In this answer, we will read what the two measurements tell us, explain the starvation and the throughput loss, show why contention is the real problem, measure it, go through the ways to reduce it, and then make the fairness decision.
1Reading the Two Measurements
Two observations point at the same thing. Before the change, most requests were fast and a few waited seconds: a long tail with a normal middle. After switching to fair mode, the tail shrank but the whole service handled 40 percent fewer requests. A lock that is lightly used would show neither effect, because with few waiters it rarely matters who goes next and the fairness flag costs almost nothing. Both effects only appear when many threads are waiting for the lock most of the time. So the first conclusion is that the lock is heavily contended, and fairness is only deciding how the pain is shared.
2Why the Non-Fair Lock Produces a Long Tail
In a non-fair ReentrantLock, a thread that calls lock() while the lock happens to be free takes it immediately, even if others are queued. When the holder unlocks, the first queued thread is woken, but it needs microseconds to be scheduled, and in that gap a running thread, often the one that just released the lock and came back for its next item, or a fresh request, takes the lock again. The woken thread finds the lock taken and parks once more.
Under light load this does not matter. Under heavy contention it can happen to the same queued thread many times in a row. Most requests are lucky and get in quickly, so the median is fine, but a few lose repeatedly and wait seconds. That is exactly the shape users reported: fast for most, very slow for a few.
3Why Fair Mode Costs 40 Percent of Throughput
In fair mode, a thread that finds others queued must join the queue. So every time the lock is released, the next owner is a parked thread that has to be woken and scheduled, and the lock stays idle until it runs. A context switch costs several microseconds. If the critical section takes, say, 10 microseconds, adding even 5 microseconds of idle time to every hand-off cuts the maximum rate at which the lock can be used by about a third. The arriving threads that would have used the gap now park as well, adding more switches and more cache misses, because each owner starts on a cold CPU cache.
So the 40 percent drop is not a surprise; it is the price of strict ordering on a busy lock. The p99 improved because waiting is now shared out evenly, not because there is less of it.
| Measure | Non-fair | Fair |
|---|---|---|
| who waits | a few unlucky threads, repeatedly | everyone, in turn |
| median latency | low | higher |
| p99 latency | seconds for losers | lower and more even |
| lock idle between owners | rarely | every hand-off, a context switch |
| throughput | high | about 40% lower here |
4The Real Problem: Contention
A lock is a queue with one server. Queueing behaves very non-linearly: if a lock is busy 50 percent of the time, waits are short; at 90 percent, they grow several times longer; near 100 percent, they become unbounded. For example, if each request holds the lock for 50 microseconds and the service handles 18,000 lock acquisitions per second, the lock is busy 18,000 x 50 us = 0.9 seconds of every second, 90 percent utilisation. At that level small bursts produce long queues, and fairness only decides who stands at the back.
So the useful question is how to make the lock less busy, either by holding it for less time or by spreading the work over more locks or none.
5Measuring Before Changing Anything
Before redesigning, we measure where the time goes. JFR, Java Flight Recorder, records events for threads blocked on monitors (jdk.JavaMonitorEnter) and for threads parked, which covers ReentrantLock (jdk.ThreadPark), with the stack trace and the duration of each wait. async-profiler in lock mode shows which locks threads wait on and for how long, as a flame graph. Inside the critical section, a CPU or wall-clock profile shows what the holder is doing: is it computing, logging, serialising or, worst of all, waiting on I/O?
Simple metrics help too: the lock's getQueueLength() sampled as a gauge, and a timer around the critical section to get the real hold time distribution. A long hold time tail often points to the cause directly, for example an occasional database call inside the lock.
6Reducing the Contention
There are three main levers, from the cheapest to the most fundamental. First, shorten the critical section: move everything that does not need the lock out of it, such as building log messages, serialising, computing values from data that is already copied, and above all any I/O. Often a critical section shrinks from tens of microseconds to under one just by copying what we need and working outside.
Second, split the lock. If the lock protects many independent items, such as accounts, sessions or cache keys, give each group its own lock, for example by striping: an array of 64 locks indexed by the key's hash. Requests for different keys then stop competing. ConcurrentHashMap's per-bin locking is the built-in version of this idea.
Third, remove the shared mutable state: use LongAdder for counters, an immutable snapshot behind a volatile reference for read-mostly data, or confine state to one thread and send it messages through a queue. When the state is not shared, there is no lock to contend on.
- Measure hold times and waitersJFR or async-profiler lock mode
- Is there I/O or heavy work under the lock?YesMove it out, re-measureNoContinue
- Does the lock guard independent items?YesSplit or stripe the lockNoContinue
- Can the shared state be removed?YesLongAdder, snapshot, confinementNoKeep the lock
- Still contended and tail matters?YesConsider fair mode, measure both goalsNoKeep non-fair
5 steps in order. Play them, or step through them one at a time.
Fairness is the last step, not the first.
7Deciding on Fairness Afterwards
Once contention is reduced, the trade-off often disappears. At 30 percent utilisation, the non-fair lock rarely starves anyone, so the tail is short and we keep its throughput. If some contention remains and the service has a strict latency objective, for example p99 under 200 ms, we test both modes against both goals with a realistic load and pick the one that meets them, writing down why. Fair mode is a legitimate choice when bounded waiting matters more than peak throughput; it is just a poor substitute for fixing an overloaded lock.
8Follow-up questions
Why did most requests stay fast in non-fair mode if the lock was so busy?
Because barging favours threads that are already running and arrive at the right moment, and most requests are lucky. The waiting is concentrated on a few threads that keep losing the race after being woken, so the median looks healthy while the tail is terrible.
Would switching to synchronized help?
Not with the root cause. synchronized is also non-fair and would show a similar tail under the same contention. The fix is to reduce how long and how often the lock is held, whichever primitive we use.
How would you verify the improvement?
With the same load test before and after, reporting p50, p99 and throughput together, plus the JFR lock wait totals. A real fix lowers lock waiting overall and improves both p99 and throughput, while a fairness change moves one at the cost of the other.
9Conclusion
In this answer, we saw that the long tail comes from a heavily contended non-fair lock, where barging lets most threads in quickly while a few lose repeatedly, and that fair mode shares the waiting evenly but adds a context switch to every hand-off, costing about 40 percent of throughput. Both point to the real problem, contention, so we measure hold times and waiters with JFR or async-profiler, shorten the critical section, split the lock or remove the shared state, and only then choose a fairness mode based on the service's latency and throughput goals.
Open with
I would read both observations as signs that the lock is heavily contended. In non-fair mode, when the lock is released the first queued thread is woken, but before it gets scheduled a running thread barges in and takes the lock, so most requests get through quickly while a few unlucky ones lose again and again and wait seconds.
Then, if they want more
That is the tail. Fair mode stops the barging, so waiting is shared evenly and p99 improves, but now every hand-off means waking a parked thread while the lock sits idle, which is several microseconds of context switch per acquisition, so throughput falls, here by 40 percent. Neither mode reduces the total waiting; they only distribute it.
So I would treat contention as the real problem. First measure: JFR's ThreadPark and JavaMonitorEnter events, or async-profiler in lock mode, to see hold times, waiters and what runs inside the lock.
Then reduce it: move I/O, logging and serialisation out of the critical section, split the lock by key with striping if it guards independent items, or remove the shared state with LongAdder, an immutable snapshot or a concurrent collection.
Once utilisation is down, the non-fair lock usually no longer starves anyone, and if some contention remains, I would test both modes against the actual latency and throughput targets and choose based on those.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.concurrent, package documentation, JLS chapter 17, Threads and Locks
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Users report that a few requests wait seconds for a shared lock while most are fast. A...": https://scrivio-interview-library.netlify.app/java/locks/15b4f4966d/