Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A team replaced synchronized with ReentrantReadWriteLock around a read-mostly map, expecting a speedup, but benchmarks show it got slower. Another service with the same lock sees writes delayed by seconds. Explain both.

The first service got slower because its critical sections are tiny map lookups, and every read lock acquisition still updates a shared counter with an atomic operation, so on many cores that contended counter costs more than the parallel reading saves. Read-write locks only pay off when reads are long and contended enough for parallel readers to matter. In the second service, the non-fair lock lets a steady stream of readers keep delaying writers; fair mode helps writers at a cost to throughput. Better options are ConcurrentHashMap, an immutable snapshot replaced on write, or StampedLock optimistic reads, always chosen with a benchmark at realistic read and write ratios.

Background to this question

Replacing a plain lock with a read-write lock is one of the most common 'optimisations' in Java code, and it often makes things worse. The reasons sit deep in how locks are implemented and how CPU caches work, so this question separates people who have measured from people who have only read the theory. In this answer, we will recap what each lock costs, explain why the read lock made the first service slower, explain why writes waited seconds in the second, look at when a read-write lock really helps, and then compare the alternatives and how to benchmark them.

1A Quick Recap of What a Lock Costs

Acquiring any lock without waiting is fast, but not free: it changes some shared memory with an atomic instruction such as compare-and-set. On a multi-core machine, that memory lives in one cache line, a 64-byte block that the CPU cores pass between them. When many cores write the same cache line, it bounces from core to core, and each transfer takes tens to hundreds of nanoseconds. This is called contention, and it is the main cost of locking under load.

A synchronized block or ReentrantLock has one such location. ReentrantReadWriteLock also has one shared state word that holds both the count of readers and the writer's hold count.

2Why the Read Lock Made the First Service Slower

The team's reasoning was that readers no longer wait for each other, so 16 reader threads would run 16 lookups at once. But look at what each reader does: it increments the shared reader count with a compare-and-set to acquire, and decrements it to release. That is two writes to the same cache line per read, from every core. The lookup itself, a HashMap.get, takes perhaps 20 to 50 nanoseconds. So most of each operation's time is spent fighting over the counter, and readers do still wait for each other, just at the hardware level instead of in the lock queue.

ReentrantReadWriteLock also does more bookkeeping than a plain lock: it tracks per-thread read hold counts so the read lock can be reentrant, which adds work on every acquisition. With a synchronized block, an uncontended or lightly contended lock is very cheap in HotSpot. So for a tiny critical section, the plain lock and the read-write lock both serialise on one cache line, and the read-write lock does more work per operation.

Java
// JMH-style measurement, 16 threads, 95% reads, map of 10,000 entries (illustrative numbers)
// Benchmark Mode Cnt Score Units
// MapBench.synchronizedGet thrpt 10 38.2 ops/us
// MapBench.readWriteLockGet thrpt 10 21.7 ops/us // slower: reader counter contention
// MapBench.concurrentHashMapGet thrpt 10 412.5 ops/us // reads take no lock at all

Notice that the numbers are illustrative; the exact ratio depends on the hardware, the JDK and the thread count, which is the point of benchmarking. But the shape is typical: for short reads, the read-write lock loses to a plain lock, and a lock-free structure wins by an order of magnitude.

3When a Read-Write Lock Pays Off

Parallel readers help when each read holds the lock long enough that the time saved by running reads together is much larger than the cost of updating the reader count. A read that walks a large structure, computes over many entries, or serialises a big object for a few microseconds or more is a candidate. Then 16 readers really do get close to 16 times the throughput of a plain lock, because the counter is touched only twice per long operation.

So the rule is not 'read-mostly data needs a read-write lock'. It is 'read-mostly data with long reads, under real contention, may benefit from one'. For short reads, it usually does not.

Read-write lock versus a plain lock
Critical sectionContentionTypical result
tens of nanoseconds (map lookup)many coresread-write lock often slower
tens of nanosecondslowabout the same, plain lock simpler
microseconds or more (scan, compute)many readersread-write lock can scale well
any length, frequent writeshighlittle gain, writers block everyone

4Why Writes Were Delayed by Seconds in the Second Service

The second service has a different problem: writer starvation. A writer can only acquire the write lock when the reader count drops to zero. If readers arrive continuously and their critical sections overlap, the count may rarely reach zero.

ReentrantReadWriteLock in its default non-fair mode does not promise any order. It has one heuristic to help writers: a new reader waits if the first thread in the queue is a writer. But readers that are already inside, readers that re-enter, and readers that arrive while the queue head is still a reader keep going. With heavy read traffic, a writer can wait a long time, and if the reads are long, seconds are possible.

Step throughA writer waiting behind overlapping readers
ReadersRead-write lockWriter
reader 1 acquires read
request write lock
wait: readers = 1
reader 2 already inside, reader 1 leaves
reader 3 re-enters, readers > 0 again
still waiting

6 messages in order. Play them, or step through them one at a time.

The count of readers seldom reaches zero, so the writer keeps waiting.

5Fair Mode Helps Writers, at a Price

new ReentrantReadWriteLock(true) puts threads in arrival order. Once a writer is waiting, readers that arrive later queue behind it, so the writer gets in as soon as the current readers leave. That bounds write latency. The price is throughput: every hand-off goes to a queued thread that must be woken, which costs a context switch, and readers lose the chance to share the lock with those already inside while a writer waits. In a read-heavy service, that can cut throughput noticeably.

Fair mode is a reasonable short-term fix for the second service if write latency matters, for example if writes are configuration updates that must take effect quickly. But it treats the symptom.

6Better Alternatives and How to Choose

For both services, the better answer is often to stop using a lock for reads. ConcurrentHashMap gives lock-free reads and fine-grained locking for writes, which fits a shared map almost perfectly. For data that changes rarely and as a whole, an immutable snapshot replaced on write is even simpler: readers read a volatile reference, writers build a new map and swap the reference. StampedLock offers optimistic reads, which take no lock and just check a version stamp afterwards, which suits very short reads of a few fields.

Java
// Immutable snapshot: readers never lock, writers copy and swap
private volatile Map<String, Rate> rates = Map.of();
Rate rate(String code) { return rates.get(code); } // one volatile read
synchronized void update(String code, Rate r) { // writers serialise among themselves
Map<String, Rate> next = new HashMap<>(rates);
next.put(code, r);
rates = Map.copyOf(next); // publish the new version
}

The snapshot costs a full copy per write, so it suits maps that are written rarely, a few times a second or less. Whatever we pick, the decision should come from a benchmark with JMH that uses the real read and write ratio, the real critical section and the real number of threads, measuring both throughput and the latency of writes, because a change that helps one can hurt the other.

7Follow-up questions

Why did the plain synchronized version do better than expected?

Because HotSpot's monitors are very efficient when critical sections are short: a thread often gets the lock by spinning briefly instead of sleeping. And with one lock word, the cost is one atomic update per operation, while the read-write lock does a similar update plus extra bookkeeping on both acquire and release.

Would StampedLock fix the writer starvation too?

Partly. Optimistic readers take no lock, so they never block a writer; the writer gets the lock and readers that overlap simply retry. That makes writes prompt. But StampedLock is not reentrant and has no conditions, so it only suits small, self-contained classes.

What would you measure in production to tell these problems apart?

Lock profiling, such as JFR's jdk.JavaMonitorEnter and jdk.ThreadPark events or async-profiler in lock mode, shows where threads wait and for how long. High total wait on the read lock with tiny hold times points to counter contention; long waits concentrated in the write path point to starvation.

8Conclusion

In this answer, we saw that the first service got slower because each read lock acquisition updates a shared counter, and for short map lookups on many cores that contended atomic update costs more than the parallelism gains; read-write locks pay off only for long, contended reads. The second service suffers from writer starvation, because in non-fair mode a steady stream of overlapping readers keeps the reader count above zero; fair mode bounds write latency but lowers throughput. ConcurrentHashMap, an immutable snapshot behind a volatile reference or StampedLock optimistic reads are usually better, and the choice should come from a benchmark with realistic ratios and thread counts.

What to say in the interviewAbout 90 seconds aloud

Open with

For the first service, the critical section is a map lookup of a few tens of nanoseconds. Taking the read lock is not free: every reader does an atomic update on the shared reader count to acquire and another to release, so on many cores that cache line bounces between cores, and readers still serialise on it, just in hardware.

Then, if they want more

ReentrantReadWriteLock also tracks per-thread hold counts, so it does more work than a plain lock, and HotSpot's synchronized is cheap for short sections. So the read-write lock lost. It only pays off when reads are long, microseconds or more, and contended enough that running them in parallel saves more than the counter costs.

For the second service, the problem is writer starvation. In non-fair mode there is no ordering promise, and with a steady stream of overlapping readers the reader count rarely reaches zero, so a writer can wait seconds. Fair mode bounds that by queuing new readers behind a waiting writer, but each handoff wakes a parked thread, so throughput drops.

For both I would look at removing read locking: ConcurrentHashMap for a shared map, an immutable snapshot behind a volatile reference if writes are rare, or StampedLock optimistic reads for tiny reads. And I would decide with a JMH benchmark using the real read-write ratio and thread count, measuring both throughput and write latency.

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.
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 "A team replaced synchronized with ReentrantReadWriteLock around a read-mostly map...": https://scrivio-interview-library.netlify.app/java/locks/c1f22ab507/