Quick revision
The short answer
The method holds the bean's single monitor across a remote call, so every caller, even one asking for an already cached symbol, waits behind each fetch, and throughput collapses to one fetch at a time. My feedback would be to keep critical sections short and never do I/O while holding a lock: use a ConcurrentHashMap, fetch outside any lock, and store in-flight futures so only one fetch per symbol runs. I would also point out that the cache never expires, so a cache library such as Caffeine is a better fit, and that locking on the bean blocks every other synchronized method on it too.
What to remember
In this answer, we saw that a synchronized method on a singleton bean held one lock across a remote call, so every request, cached or not, queued behind each fetch and throughput fell to about 1 / fetch time. The review feedback is to keep critical sections short and never do I/O under a lock, to use a ConcurrentHashMap with in-flight futures so cached lookups never wait and each symbol is fetched once, to adopt a cache library with expiry and size limits, and to remember that locking the bean also blocks its other synchronized methods.
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 method holds the bean's single monitor across a remote call, so every caller, even one asking for an already cached symbol, waits behind each fetch, and throughput collapses to one fetch at a time. My feedback would be to keep critical sections short and never do I/O while holding a lock: use a ConcurrentHashMap, fetch outside any lock, and store in-flight futures so only one fetch per symbol runs. I would also point out that the cache never expires, so a cache library such as Caffeine is a better fit, and that locking on the bean blocks every other synchronized method on it too.
Why this question is asked
This is one of the most common performance bugs in Spring services: a method made synchronized to fix a race, which works perfectly in a unit test and caps throughput in a load test. The reviewer's job is to explain why and to suggest a design that keeps the correctness without the queue. Interviewers ask it to see whether we can reason about what a lock covers and what it costs. In this answer, we will see what the lock actually serialises, do the arithmetic for a cold cache, look at why a plain ConcurrentHashMap is not quite enough, write the version with in-flight futures, and finish with the expiry and bean-locking issues.
1What the Lock Actually Covers
The bean is a Spring singleton, so all request threads share one instance, and a synchronized instance method locks that one instance. Inside the lock, the method checks the map, possibly calls pricingClient.fetch(symbol) over the network, stores the result and returns it. So the critical section, the code that runs while the lock is held, includes a remote call.
That means only one request in the whole service can be anywhere inside getQuote at a time. A request for AAPL that is already cached still has to wait until the current fetch for MSFT finishes, even though it needs nothing from the network.
2The Arithmetic of a Cold Cache
Say the pricing service answers in 250 ms. With a cold cache, every new symbol is a fetch, and fetches run strictly one after another, so the service can complete at most 1 / 0.25 = 4 fetches per second, however many threads or cores it has. That matches the load test: a few requests per second.
The cached requests do not escape. If 100 requests arrive in a second and 5 of them need fetches, the 95 cached ones queue behind those fetches too, and their latency becomes up to 5 x 250 ms = 1.25 seconds. One slow fetch, say a 10-second timeout, freezes every quote request for 10 seconds.
6 messages in order. Play them, or step through them one at a time.
A cached lookup costs as much as the slowest fetch in front of it.
3The Rule: Short Critical Sections, No I/O Under a Lock
The general feedback is that a lock should protect only the brief moment when shared memory is read or changed, typically microseconds. Network calls, database queries and file I/O take milliseconds to seconds and can hang, so holding a lock across them turns every slow response into a queue for the whole service. It also raises the risk of deadlock if the remote call ends up needing another lock.
The original code used synchronized to solve a real problem: HashMap is not thread-safe, and without coordination two threads could fetch the same symbol twice. So the fix must keep the map safe and avoid duplicate fetches, without holding a lock during the fetch.
4A First Step: ConcurrentHashMap and Fetch Outside the Lock
A ConcurrentHashMap is safe for concurrent reads and writes without a global lock, so cached lookups never wait. A simple version fetches outside any lock and stores the result with putIfAbsent.
Throughput is now fine, but there is a catch: when a popular symbol is not cached, many requests miss at once and all fetch it, a cache stampede. Using cache.computeIfAbsent(symbol, pricingClient::fetch) avoids duplicates, but ConcurrentHashMap holds a lock on that hash bin while the function runs, so a remote call inside it can block other keys in the same bin and must not take long. The documentation says the computation should be short and simple.
5A Better Fix: Store In-Flight Futures
The pattern that solves both problems puts a future into the map instead of a value. The first request for a symbol inserts a CompletableFuture and starts the fetch; later requests find the same future and wait on it. Inserting the future is instant, so computeIfAbsent's bin lock is held only for microseconds.
Notice the details that make it production-safe: an explicit executor for fetches, a timeout on waiting, and removing a failed future so the next request can retry. This is close to what Caffeine's AsyncLoadingCache does internally.
6Two More Review Points: Expiry and the Bean's Monitor
The cache never refreshes or evicts. Prices change, and the map grows with every symbol ever requested. A cache library such as Caffeine gives us expiry (expireAfterWrite or refreshAfterWrite), a maximum size, statistics, and the one-load-per-key behaviour, so we should use it rather than grow our own. In Spring, @Cacheable backed by Caffeine is another option, with the note that by default it does not prevent concurrent loads of the same key unless sync = true.
Finally, a synchronized method locks the bean itself. Any other synchronized method on the same bean, say a refreshAll() or a stats() method, also waits behind every fetch, and any code elsewhere that synchronizes on the bean joins the same queue. Even where a lock is needed, a private lock object keeps it scoped.
7Follow-up questions
Is computeIfAbsent with the remote call directly inside it acceptable?
It prevents duplicate fetches, but ConcurrentHashMap locks the hash bin during the mapping function, so other keys that hash to the same bin wait, and the documentation asks for short computations. A slow or hanging remote call there can block unrelated keys and even recursive updates. Storing a future keeps the bin lock short.
What would you measure after the change?
Throughput and latency under the same load test with a cold and a warm cache, the number of fetches per symbol to confirm deduplication, the pricing client's latency and error rate, and the cache hit ratio and size, which Caffeine can report through Micrometer.
Should failed fetches be cached?
Usually not for long. Caching a failure briefly, say for a second, can protect a struggling pricing service from a flood of retries, but caching it forever means a single timeout makes a symbol unavailable until restart. That is why the example removes failed futures.
8Conclusion
In this answer, we saw that a synchronized method on a singleton bean held one lock across a remote call, so every request, cached or not, queued behind each fetch and throughput fell to about 1 / fetch time. The review feedback is to keep critical sections short and never do I/O under a lock, to use a ConcurrentHashMap with in-flight futures so cached lookups never wait and each symbol is fetched once, to adopt a cache library with expiry and size limits, and to remember that locking the bean also blocks its other synchronized methods.
Open with
The core problem is that the lock covers a remote call. The bean is a singleton, so synchronized on the method means one lock for the whole service, and while one thread is fetching a quote, every other request waits, even for symbols that are already cached.
Then, if they want more
With a 250 millisecond pricing call and a cold cache, that caps the service at about four fetches per second, which is what the load test shows, and one slow fetch freezes everything. My feedback would be to keep critical sections short and never do I/O while holding a lock.
I would switch to a ConcurrentHashMap so cached lookups never block. To avoid a stampede of duplicate fetches for the same symbol, I would store in-flight CompletableFutures: computeIfAbsent inserts a future that starts the fetch on a dedicated executor, other callers wait on that same future with a timeout, and failed futures are removed so we can retry.
I would not put the remote call itself inside computeIfAbsent, because it holds the bin lock during the function. I would also note that this cache never expires or evicts, so I would suggest Caffeine, which gives expiry, size limits and one load per key. And synchronized on the bean blocks any other synchronized method on it too.
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 "In a code review you see": https://scrivio-interview-library.netlify.app/java/synchronization/f84e6ffbf8/