Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

A service uses a synchronized LinkedHashMap LRU cache for product lookups. At 20,000 requests per second, thread dumps show many threads BLOCKED on the cache monitor. Design a replacement and explain why the original contends.

The original contends because an access-ordered LinkedHashMap moves an entry to the end of its linked list on every get(), so every read is a write that needs the exclusive monitor, and at 20,000 requests per second all request threads queue behind one lock. I would replace it with a mature concurrent cache such as Caffeine, which records reads in buffers and applies them to its eviction policy asynchronously, so reads never take a global lock, and whose Window TinyLFU policy usually gives a better hit rate than pure LRU. The design then decides the size bound or weight function, expiry and refresh, and exposes hit rate and eviction metrics; building the same on ConcurrentHashMap with approximate eviction is possible but costly and risky.

Why this question is asked

A synchronized LinkedHashMap is the textbook LRU cache, and it works well until traffic grows. Then a cache meant to make lookups faster becomes the slowest part of the request, and thread dumps fill with BLOCKED threads waiting on the same object. Interviewers ask this design question to see whether we can explain why reads contend, not just that they do, and whether we can design a replacement with the right policy, bounds and observability. In this answer, we will recap how the original cache works, explain the contention, look at how Caffeine avoids it, design the replacement's configuration, and discuss when a home-grown alternative is justified.

1A Quick Recap of the Original Cache

The cache is a LinkedHashMap created with accessOrder set to true and a removeEldestEntry override, so it evicts the least recently used entry when full. Because LinkedHashMap is not thread-safe, it is wrapped with Collections.synchronizedMap, which puts a synchronized block on one monitor object around every method.

A thread trying to enter a synchronized block while another thread holds the monitor waits in state BLOCKED. Thread dumps showing many threads BLOCKED on the same monitor, waiting to lock the synchronized map, are the direct evidence of lock contention.

2Why Every Read Needs the Lock

In access-order mode, get() does more than read. After finding the entry, LinkedHashMap unlinks it from its position in the doubly linked list and relinks it at the end, which updates up to four references. The Javadoc states it plainly: in an access-ordered map, merely calling get() is a structural modification. Two threads doing that at once could corrupt the list, so the lock is not optional, and a read-write lock would not help, because every read is a write.

So at 20,000 requests per second, every lookup goes through one critical section in turn. Even if each takes only a microsecond, the lock is busy a large share of the time, and as more threads arrive they wait in line, so tail latency climbs faster than load. Things get much worse if the code does get(), then loads from the database on a miss, and puts the result back inside the same synchronized block, because then the lock is held for a network round trip.

Step throughTwo request threads on the synchronized LRU map
Thread AMap monitorThread B
lock, get(p1): find entry, move it to the tail
lock: BLOCKED, A holds the monitor
unlock
lock acquired, get(p2): move to tail
unlock

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

Every read reorders the list, so every read waits for every other read.

3How Caffeine Avoids the Global Lock

Caffeine stores entries in a ConcurrentHashMap, so finding a value never takes a global lock. The difficult part, keeping the eviction policy up to date with every access, is decoupled from the read. When a thread reads an entry, it records the access in a small striped ring buffer, an array that several threads can append to with cheap atomic operations, and returns the value immediately. If a buffer is full, the event is simply dropped, which is acceptable because the policy only needs a good sample of accesses.

Writes are recorded in a separate write buffer that is not lossy. A maintenance task, run by whichever thread manages to acquire a lock with tryLock, or on an executor, drains the buffers and applies the changes to the eviction policy in a batch. Readers never wait for that task. So the cost of a read is a hash lookup plus a buffered append, and contention on any single lock disappears from the request path.

Step throughInside a Caffeine cache
  1. Request threadsget and put
  2. ConcurrentHashMapthe data: lock-free reads
  3. Read and write buffersaccesses recorded, reads may be dropped when full
  4. Maintenance taskdrains buffers under tryLock, in batches
  5. W-TinyLFU policywindow, probation and protected regions, frequency sketch

5 layers, from the top down. Step through them one at a time.

4A Better Policy Than Pure LRU

LRU evicts whatever was used least recently, which is easily fooled. A burst of one-off lookups, such as a crawler walking the whole catalogue, pushes out the popular products. Caffeine uses Window TinyLFU. New entries first enter a small window region managed by LRU. When an entry leaves the window, it competes with the main region's eviction candidate, and a compact frequency sketch, a probabilistic counter of how often each key has been seen recently, decides which of the two is more likely to be used again. One-off keys lose that contest and are dropped, while frequently used keys stay. The policy also adapts the window size to the workload. On most real traces this gives a noticeably higher hit rate than LRU at the same size.

5Designing the Replacement

The configuration should be decided per cache, from what the data is and how stale it may be.

Java
LoadingCache<String, Product> products = Caffeine.newBuilder()
.maximumWeight(200_000_000) // about 200 MB of products
.weigher((String sku, Product p) -> p.approxBytes())
.expireAfterWrite(Duration.ofMinutes(30)) // never serve data older than this
.refreshAfterWrite(Duration.ofMinutes(5)) // reload in the background for hot keys
.recordStats()
.build(sku -> catalog.load(sku)); // one load per key, even under concurrency
CaffeineCacheMetrics.monitor(meterRegistry, products, "products"); // hit rate, evictions, load time

A size bound, maximumSize for a count or maximumWeight with a weigher for bytes, keeps the heap predictable. expireAfterWrite sets the staleness budget, and refreshAfterWrite reloads popular entries in the background so callers rarely wait on a reload. A loading cache also ensures that if 50 threads miss on the same key at once, only one calls the catalogue, which a get-then-put map does not. Finally, recordStats() with Micrometer exposes hit rate, eviction count and load latency, which we put on the service dashboard. In a Spring application the same can be configured through the cache abstraction with a CaffeineCacheManager.

6What About Staying on the JDK?

If a dependency is truly not allowed, we can build an approximate cache on ConcurrentHashMap: store a last-access timestamp in each value, and when the size exceeds the bound, have one thread sample some entries and evict the oldest. That avoids the global lock, but we would be writing and testing our own eviction, size accounting, loading and statistics, with subtle races in each. It is weeks of work to reach a fraction of what a mature library already does, so I would only choose it with a strong reason.

7Follow-up questions

How would you verify the new cache's hit rate before rollout?

In two ways. Offline, I would capture a trace of the cache keys from production logs for a busy hour and replay it through both an LRU of the same size and the new Caffeine configuration, which gives hit rates for the same traffic; Caffeine's project also ships a simulator for exactly this. Online, I would run the new cache in shadow mode on a canary: populate it alongside the old one, record its statistics without serving from it, then switch the canary to serve from it and compare hit rate, latency and database load with the other instances before rolling out.

Would a ReentrantReadWriteLock fix the original cache?

No. In access order, get() modifies the linked list, so every read would need the write lock. A read-write lock would only add overhead. It helps only for an insertion-ordered map, which no longer gives LRU behaviour.

Does the move to virtual threads change anything?

It makes the old design worse, not better. Many more concurrent requests contend on the same monitor, and on JDKs before 24, blocking inside synchronized could pin the virtual thread to its carrier. Caffeine's read path does not hold a lock, so it suits virtual threads well.

8Conclusion

In this answer, we saw that a synchronized, access-ordered LinkedHashMap contends because every get() reorders the linked list, which makes each read a write that needs the single monitor, so at 20,000 requests per second all threads serialize. Caffeine avoids that by reading from a ConcurrentHashMap and recording accesses in buffers that a maintenance task applies asynchronously, and its Window TinyLFU policy usually beats pure LRU on hit rate. The replacement design sets a size or weight bound, expiry and refresh, uses a loading cache to avoid duplicate loads, and exposes hit rate and eviction metrics, while a home-grown ConcurrentHashMap cache with approximate eviction remains possible but costly and risky.

What to say in the interviewAbout 100 seconds aloud

Open with

The original cache contends because it is an access-ordered LinkedHashMap. In that mode, get does not just read: it moves the entry to the end of the linked list, so every read is a structural modification.

Then, if they want more

That is why it has to be wrapped in a synchronized map, and why a read-write lock would not help.

At 20,000 requests a second every lookup goes through one monitor in turn, so threads pile up BLOCKED and tail latency grows faster than load, and it is even worse if the miss path loads from the database inside the lock. I would replace it with Caffeine.

It keeps the data in a ConcurrentHashMap, so lookups do not take a global lock, and it records each access in a striped buffer that a maintenance task drains in batches under a tryLock, so reads never wait for policy updates.

Its Window TinyLFU policy uses a frequency sketch to decide admission, so a burst of one-off keys cannot flush the popular products, and the hit rate is usually higher than LRU.

For the design I would set a maximum weight with a weigher based on product size, an expireAfterWrite that matches how stale product data may be, refreshAfterWrite for hot keys, and use a loading cache so concurrent misses on one key cause one load. I would enable recordStats and publish hit rate, evictions and load time through Micrometer.

Before rollout I would replay a production key trace through both policies, and run the new cache in shadow mode on a canary to compare hit rates.

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 service uses a synchronized LinkedHashMap LRU cache for product lookups. At 20,000...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/020d0002ad/