Quick revision
The short answer
The hit rate is near zero because each request builds a new RequestDto, and once the request ends nothing refers to that DTO, so the entry can disappear at the very next garbage collection. WeakHashMap ties an entry's lifetime to whether its key is still reachable, not to whether the result is useful or memory is short, so it is not a cache. A bounded cache such as Caffeine, with a size limit and expiry and keyed by an immutable value, is the right design; WeakHashMap is the right tool for metadata attached to objects that something else owns.
What to remember
In this answer, we saw that the WeakHashMap cache missed because every entry was tied to a per-request DTO that became unreachable when the request ended, so the next young collection removed it. WeakHashMap ties lifetime to key reachability, not to usefulness or memory pressure, which makes it unsuitable as a cache. A bounded Caffeine cache with size and expiry, keyed by an immutable record of the relevant inputs, fixes the design. WeakHashMap remains useful for metadata attached to objects owned elsewhere, and ClassValue is the right tool for per-Class data because it avoids class loader leaks.
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 hit rate is near zero because each request builds a new RequestDto, and once the request ends nothing refers to that DTO, so the entry can disappear at the very next garbage collection. WeakHashMap ties an entry's lifetime to whether its key is still reachable, not to whether the result is useful or memory is short, so it is not a cache. A bounded cache such as Caffeine, with a size limit and expiry and keyed by an immutable value, is the right design; WeakHashMap is the right tool for metadata attached to objects that something else owns.
Why this question is asked
Caching expensive work is one of the most common optimisations in a service, and it is also easy to get wrong in ways that do not show up in tests. A cache that never hits costs memory and CPU and gives nothing back. Interviewers ask this scenario because it tests whether we understand what WeakHashMap actually promises, and whether we can design a real cache with sensible limits. In this answer, we will recap how WeakHashMap decides an entry's lifetime, trace why this cache misses, design a proper replacement, and then look at the cases where WeakHashMap and its cousin ClassValue are the correct tools.
1A Quick Recap of How WeakHashMap Keeps Entries
WeakHashMap holds each key through a weak reference, a reference that does not stop the garbage collector from reclaiming the object. As long as some other part of the program holds the key strongly, the entry stays. As soon as the key is reachable only through the map, the collector may reclaim it, and the map drops the entry on its next operation.
So the rule is simple: an entry lives exactly as long as its key object is in use somewhere else. The map knows nothing about how often an entry is read, how expensive it was to compute, or how much memory is free.
2Tracing Why the Cache Misses
Let us follow two identical requests through the teammate's code.
6 messages in order. Play them, or step through them one at a time.
The entry lived only as long as the first request's DTO.
Notice that even if RequestDto has a correct equals and hashCode, and request 2 is identical to request 1, the entry from request 1 was tied to dto#1, a short-lived object. In a busy service, young collections happen many times a second, and almost every short-lived object dies in the first one. So most entries vanish before a second request can use them, which matches the near zero hit rate.
There is a second cost. The map still pays for every miss: it hashes the DTO, computes the result, stores it, and later expunges it. So the cache adds work and garbage while saving almost nothing.
3Why WeakHashMap Is Not a Cache
A cache needs a policy that answers one question: when memory is limited, which entries are worth keeping? Good policies use how recently or how often an entry was used, and how old it is. WeakHashMap answers a different question: is anybody else still using this exact key object? For keys created per request, the answer is almost always no, so entries die immediately. For keys held forever, such as interned strings, the answer is always yes, so entries never die and the map grows without bound. Neither outcome has anything to do with usefulness or memory pressure.
4A Better Design: A Bounded Cache With a Value Key
We want entries that survive across requests, a limit on how many we keep, and an expiry so stale results do not live forever. Caffeine is the standard library for this in Java, and Spring's cache abstraction supports it directly. The key should be an immutable value that captures exactly the inputs that affect the result, and a record is the easiest way to get a correct equals and hashCode.
Notice what changed. The entry's lifetime is now decided by the cache policy, so a key created in request 1 and an equal key created in request 2 find the same entry. The key holds only the fields that matter, so two DTOs that differ in an irrelevant field, such as a trace id, still share a result. And maximumSize means the cache can never grow beyond what we planned for. Caffeine's eviction uses both frequency and recency, which keeps popular entries even under scans of one-off keys.
We should also size it from data: estimate how many distinct keys appear in ten minutes and how large a Result is, then check the hit rate and eviction count from recordStats() in production.
5When WeakHashMap Is the Right Tool
WeakHashMap fits when we want to attach extra data to an object that some other code owns and controls the lifetime of, and we want our data to vanish when that object does. For example, a library may want to remember per-connection or per-document state without forcing its caller to call a cleanup method. The key is the owned object, it is compared by identity in practice because such objects rarely override equals, and the value must not refer back to the key.
For per-Class metadata, such as a cached list of reflected fields for a serializer, the JDK offers ClassValue, which is designed for exactly this. A WeakHashMap<Class<?>, Meta> can leak a whole class loader if the value strongly references the class, which is common with reflection data, and that prevents application redeploys from freeing memory. ClassValue stores the value with the class itself, so it goes away when the class is unloaded.
6Follow-up questions
Would SoftReference values fix the teammate's cache?
They would make entries live longer, because soft references are cleared only when the JVM needs memory, but they move the cache policy into the garbage collector. Under pressure, the collector may clear most entries at once, causing a stampede of recomputation exactly when the system is busiest, and soft references add work to every collection. A bounded cache with explicit size and expiry is far more predictable.
How would you choose maximumSize?
From the working set and the entry size. If logs show about 30,000 distinct keys per ten minutes and each result is about 2 KB, then 50,000 entries cost roughly 100 MB plus overhead, and we check that fits our heap budget. Then we watch hit rate and evictions in production and adjust. Caffeine can also bound by weight with maximumWeight and a weigher when entries vary in size.
Why should the cache key not be the DTO itself?
The DTO may carry fields that do not affect the result, such as request ids or timestamps, which would make every key unique. It may also be mutable, and a key that changes after insertion lands in the wrong bucket. A small record of exactly the relevant inputs gives stable, correct equality.
7Conclusion
In this answer, we saw that the WeakHashMap cache missed because every entry was tied to a per-request DTO that became unreachable when the request ended, so the next young collection removed it. WeakHashMap ties lifetime to key reachability, not to usefulness or memory pressure, which makes it unsuitable as a cache. A bounded Caffeine cache with size and expiry, keyed by an immutable record of the relevant inputs, fixes the design. WeakHashMap remains useful for metadata attached to objects owned elsewhere, and ClassValue is the right tool for per-Class data because it avoids class loader leaks.
Open with
The hit rate is near zero because the key is a DTO created for each request. WeakHashMap only keeps an entry while the key object is strongly reachable somewhere else.
Then, if they want more
When the request ends, nothing refers to that DTO, so at the next young GC, which in a busy service is every fraction of a second, the weak reference is cleared and the entry disappears. The next identical request creates an equal but different DTO and misses.
So WeakHashMap is not a cache: it ties lifetime to reachability of one key object, not to usefulness or memory pressure. I would replace it with a bounded cache like Caffeine, with maximumSize sized from the expected working set, expireAfterWrite for staleness, and recordStats so we can see the hit rate.
The key would be a small immutable record holding only the inputs that affect the result, not the DTO, so irrelevant fields like trace ids do not make every key unique.
WeakHashMap is the right tool when I want to attach data to objects owned by someone else and have it disappear with them, as long as the value does not refer to the key. For per-Class metadata, I would use ClassValue, which is built for that and avoids class loader leaks.
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.HashMap, API documentation, The Collections Framework, overview
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 teammate used a WeakHashMap<RequestDto, Result> as a cache for expensive computations...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/6acb841e1f/