Quick revision
The short answer
The entries are never removed because the value, Meta, holds a strong reference to its own key, and WeakHashMap holds its values strongly. So every key stays strongly reachable through the map's own value, the weak reference to the key is never cleared, and the entry never goes away. We fix it by not referencing the key from the value, or by holding it through a WeakReference inside Meta; and we also avoid String literals or interned strings as keys, because those stay strongly reachable and are never removed either.
What to remember
In this answer, we saw why a WeakHashMap whose values reference their keys never removes entries: values are held strongly, so the path from the map through the value to the key keeps the key strongly reachable, and its weak reference is never cleared. We fixed it by removing the key from the value or holding it through a WeakReference, and saw that String literals, interned strings, cached boxed values and enum constants are never removed for a similar reason: something else keeps them strongly reachable.
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 entries are never removed because the value, Meta, holds a strong reference to its own key, and WeakHashMap holds its values strongly. So every key stays strongly reachable through the map's own value, the weak reference to the key is never cleared, and the entry never goes away. We fix it by not referencing the key from the value, or by holding it through a WeakReference inside Meta; and we also avoid String literals or interned strings as keys, because those stay strongly reachable and are never removed either.
Why this question is asked
WeakHashMap looks like the perfect tool for attaching extra data to objects that some other part of the program owns: when the owner drops the object, the entry should vanish by itself. When it does not, the map turns into a slow memory leak that only shows up after days in production. Interviewers like this question because the bug is a single line, and finding it requires thinking about reachability rather than about the map. In this answer, we will recap how WeakHashMap works, reproduce the leak, trace why the key stays reachable, fix it, and look at keys that can never be removed.
1A Quick Recap of WeakHashMap
WeakHashMap is a hash map whose entries hold their keys through weak references. A weak reference does not keep its object alive: once nothing else refers to the key object strongly, the garbage collector may clear the reference, and the cleared entry is put on an internal reference queue.
The map does not remove entries the moment the GC runs. Instead, on most map operations, such as get, put and size, it first drains its reference queue and removes the entries whose keys were cleared. That is called expunging stale entries.
The values, though, are held normally, with strong references. That detail is the whole story of this bug.
2Reproducing the Leak
Here is the code from the question in a small test. The key class has no special behaviour; Meta stores the key and some information.
Notice that our own variable no longer holds the key, and the GC did run. Yet the entry survives every collection. In production, with thousands of keys per minute, the map grows until the heap fills.
3Why the Key Stays Reachable
Let us follow the references from a root. The map itself is reachable, for example from a static field. The map holds its internal table, the table holds the entry, and the entry holds the value strongly. The value is our Meta, and Meta has a field key, a normal strong reference to the Key object.
- GC rootstatic field holding the map
- WeakHashMap tablestrong
- Entrykey: weak, value: strong
- Meta (the value)strong
- Meta.key fieldstrong reference back to the key
- Key objectstrongly reachable, so the weak key is never cleared
6 steps in order. Play them, or step through them one at a time.
So there is a path of strong references from a root to the key: map, entry, value, Meta.key, Key. The weak reference inside the entry does not matter, because the key is strongly reachable anyway. A weak reference is only cleared when its object is reachable through nothing stronger, and here the map itself provides something stronger. The map keeps its own key alive.
The general rule is: in a WeakHashMap, a value must never reference its own key, directly or indirectly. An indirect path counts too, for example a value that holds a listener that holds the key, or a lambda that captured it.
4Fixing It
The cleanest fix is to remove the key from the value. The map already associates the value with the key, so Meta rarely needs it.
Notice that in the second version every user of key() must handle null, because the key may already have been collected. That is the price of not keeping it alive.
A related point: WeakHashMap compares keys with equals() and hashCode(), not identity. If the goal is to attach metadata to specific object instances, an identity-based weak map, such as a Caffeine cache built with weakKeys(), which compares keys by identity, may match the intent better.
5Keys That Are Never Removed
Even with a correct value, some keys can never be cleared, because something else in the JVM keeps them strongly reachable. String literals are interned: the JVM keeps them in its string table, and the class that contains the literal refers to it, so a key like "config" stays reachable as long as that class is loaded. The same is true for strings passed through intern(), for the cached Integer values from -128 to 127 returned by Integer.valueOf, and for enum constants.
So WeakHashMap only makes sense with keys whose lifetime is controlled by their owner, usually ordinary objects created at runtime.
6Follow-up questions
How would you find this leak in production?
A heap dump shows it directly. In a tool such as Eclipse MAT, the WeakHashMap appears with a large retained size, and the path to GC roots for one of its Key objects, excluding weak references, goes through the map's own value. That path, map entry value Meta key, is exactly the bug. A steadily rising heap after GC and a growing map size metric point to it before we take the dump.
Does calling System.gc() more often help?
No. The collector cannot clear the weak reference because the key is strongly reachable through the value. No amount of collection changes that. The only fix is breaking the strong path.
When are cleared entries actually removed?
WeakHashMap removes them lazily, the next time a method such as get, put, size or iteration runs and drains its reference queue. A map that is never touched again keeps its cleared entries, and their values, until it is used or itself becomes unreachable.
7Conclusion
In this answer, we saw why a WeakHashMap whose values reference their keys never removes entries: values are held strongly, so the path from the map through the value to the key keeps the key strongly reachable, and its weak reference is never cleared. We fixed it by removing the key from the value or holding it through a WeakReference, and saw that String literals, interned strings, cached boxed values and enum constants are never removed for a similar reason: something else keeps them strongly reachable.
Open with
WeakHashMap holds its keys through weak references, but it holds its values strongly. In this code the value is new Meta of key and info, so Meta has a normal field pointing back at its own key.
Then, if they want more
That creates a strong path from the map to the key: the map holds the entry, the entry holds the value strongly, and the value holds the key strongly.
A weak reference is only cleared when its object is reachable through nothing stronger, so even after the owner drops the key, the map keeps it alive through its own value, and the entry is never expunged. Calling System.gc more often does not help. The fix is to break that strong path.
The simplest way is to remove the key from Meta, since the map already associates them. If Meta genuinely needs the key, it should hold it through a WeakReference and handle null when the key is gone.
I would also check what the keys are: String literals and interned strings live in the JVM's string table and stay strongly reachable, and the same goes for cached small Integers and enum constants, so entries with those keys are never removed either.
To find this in production, I would take a heap dump and look at the path to GC roots for one key, excluding weak references; it will go straight through the map's value.
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
- HotSpot Garbage Collection Tuning Guide, JDK 21
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 uses WeakHashMap<Key, Meta> to attach metadata to keys owned elsewhere, but...": https://scrivio-interview-library.netlify.app/java/garbage-collection/382b8eac2f/