Quick revision
The short answer
A Spring @Service is a singleton shared by every request thread, and its HashMap is not thread-safe, so concurrent puts can corrupt the map or lose entries, and the check-then-act in get() lets two threads both see null and both load the same key. We fix it with a ConcurrentHashMap and computeIfAbsent, which loads each key once, keeping load short or storing futures if it is slow; and because rates change, a cache library with expiry such as Caffeine is usually better. A test that calls get from many threads at once proves the fix.
What to remember
In this answer, we saw that a singleton bean is shared by every request thread, so its HashMap is accessed concurrently even though HashMap is not thread-safe, leading to corrupted state and lost entries, and the check-then-act in get() lets two threads load the same key. ConcurrentHashMap.computeIfAbsent fixes both races if the load is short; storing futures handles slow loads; and a cache library such as Caffeine adds the expiry that changing rates need. A test that releases many threads at once and counts loads proves the fix.
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.
A Spring @Service is a singleton shared by every request thread, and its HashMap is not thread-safe, so concurrent puts can corrupt the map or lose entries, and the check-then-act in get() lets two threads both see null and both load the same key. We fix it with a ConcurrentHashMap and computeIfAbsent, which loads each key once, keeping load short or storing futures if it is slow; and because rates change, a cache library with expiry such as Caffeine is usually better. A test that calls get from many threads at once proves the fix.
Why this question is asked
Caching inside a singleton bean is one of the most common races in Spring applications, because the code looks perfectly normal for single-threaded Java. Interviewers use it to check whether we remember that beans are shared, whether we can find both the data-structure problem and the logic problem, and whether we know the subtleties of the obvious fix. In this answer, we will recap why singleton beans are shared, find the two races in the code, fix them with ConcurrentHashMap.computeIfAbsent, handle slow loads and expiring rates, and write a test that would catch the bug.
1A Quick Recap: Singleton Beans Are Shared
By default, every Spring bean is a singleton: the container creates one instance and injects that same instance everywhere. In a web application, requests run on many threads at once, so when 200 requests call rateCache.get(...) at the same moment, they all run on the same RateCache object and touch the same HashMap field.
HashMap is not thread-safe. Its Javadoc says that if multiple threads access it concurrently and at least one modifies it, access must be synchronized externally. Nothing in RateCache does that. The final keyword on the field only means the reference cannot change; the map it points to can still be modified by any thread.
2Finding the Two Races
Here is the code from the question with the problem spots marked.
8 messages in order. Play them, or step through them one at a time.
Duplicate loads, and two unsynchronized puts on a HashMap.
The first race is inside HashMap itself. A put() can trigger a resize, which moves every entry into a new, larger table. If two threads put at the same time, or one thread reads while another resizes, the map can lose entries, report the wrong size, or return null for a key that is present. Very old JDKs could even form a loop in a bucket, so a later get() spun forever; current JDKs fail differently, but still silently.
The second race is in our own logic and would exist even with a thread-safe map. get() checks whether the key is absent and then acts on that answer, but between the check and the put, another thread can make the same check. Both see null, both call load("EUR"), and both put. With a slow load, such as a call to a rates service, a burst of requests for a new currency sends dozens of identical calls downstream.
3Fixing It With ConcurrentHashMap.computeIfAbsent
ConcurrentHashMap is a thread-safe map designed for many concurrent readers and writers. Its computeIfAbsent method fixes both races at once: it checks for the key and, if absent, runs the loading function and stores the result as one atomic operation per key.
Notice the catch. While the function for a key runs, other threads that call computeIfAbsent for the same key wait, and so may threads updating other keys that happen to fall in the same internal bin. So the function must be short and must not update the same map. That is fine for a quick computation, but not for a network call that takes 300 ms.
4When load() Is Slow: Store Futures
If loading is slow, we store a future in the map instead of the value. computeIfAbsent then only creates the future, which is instant, and the slow work runs outside the map's internal locking. Every thread that asks for the same key gets the same future and waits on it, so the load still happens once.
The remove(c, f) call only removes the entry if it is still the failed future, so a later successful load by another thread is not thrown away.
5Rates Change: Use a Cache With Expiry
Both versions above keep a rate forever. Exchange rates and pricing rates change, so a cache needs expiry, and an unbounded map of every key ever seen also needs a size limit. Rather than adding those by hand, we use a cache library. Caffeine provides both, and it also loads each key once under concurrency.
In Spring we can get the same with @Cacheable("rates") on the load method and Caffeine configured as the cache provider, with sync = true on the annotation so that concurrent misses for one key load only once.
6Testing It From Many Threads
A concurrency fix needs a concurrent test. We start many threads at the same instant with a latch, have them all request the same key, and count how many times load ran.
With the original HashMap version, the count is usually greater than 1, which proves the duplicate loads; with computeIfAbsent or Caffeine it is exactly 1. The sleep in the fake loader widens the race window.
7Follow-up questions
Would making get() synchronized be a valid fix?
It is correct, because only one thread at a time could check and put, but it serializes every lookup, including hits for keys already cached, and holds the lock during the slow load. ConcurrentHashMap or a cache library gives correctness without that bottleneck.
Why not use Collections.synchronizedMap?
It makes each single call such as get or put thread-safe, but our check-then-act spans two calls, so two threads can still both see null and both load. We would still need to lock around the whole sequence, which brings back the bottleneck of a synchronized method.
Can ConcurrentHashMap store a null rate for unknown currencies?
No, ConcurrentHashMap does not allow null keys or values, and if the function passed to computeIfAbsent returns null, nothing is stored. For unknown currencies, either throw an exception or store an explicit marker value such as an Optional or a special Rate.
8Conclusion
In this answer, we saw that a singleton bean is shared by every request thread, so its HashMap is accessed concurrently even though HashMap is not thread-safe, leading to corrupted state and lost entries, and the check-then-act in get() lets two threads load the same key. ConcurrentHashMap.computeIfAbsent fixes both races if the load is short; storing futures handles slow loads; and a cache library such as Caffeine adds the expiry that changing rates need. A test that releases many threads at once and counts loads proves the fix.
Open with
The bean is a Spring singleton, so every request thread uses the same RateCache instance and the same HashMap. HashMap is not thread-safe, and there are two races here.
Then, if they want more
First, concurrent puts, or a read during a resize, can corrupt the map: lost entries, wrong size, nulls for keys that exist, and in old JDKs even an infinite loop.
Second, get is check-then-act: two threads can both see null for EUR, both call load, and both put, so a burst of requests for a new key sends duplicate calls to the rates service. Final on the field does not help; it only protects the reference.
The fix is a ConcurrentHashMap with computeIfAbsent, which does the check, the load and the put atomically per key, so load runs once and other threads wait for that result. The catch is that the function runs while the map holds an internal lock for that bin, so it must be short.
If load is a slow remote call, I store a CompletableFuture in the map instead, and remove it if it fails. Since rates change, I would actually use a cache library like Caffeine with expireAfterWrite and a maximum size, or @Cacheable with sync true.
And I would add a test: 32 threads released together by a latch, all asking for the same key, asserting that load ran exactly once.
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 "This Spring singleton bean is called by many request threads. Find the race and fix it.": https://scrivio-interview-library.netlify.app/java/concurrency-problems/f5f091b3e7/