WeakHashMap
WeakHashMap is a map whose keys are weak references. When nothing else refers to a key, the garbage collector can reclaim it and the entry disappears. Values are ordinary strong references.
Detailed Explanation
A normal HashMap keeps keys and values alive. If you use it as a cache keyed by a large object, the cache itself prevents collection. WeakHashMap wraps each key in a WeakReference. When the caller drops the last strong reference to that key object, the next GC can clear the reference. The map later expunges the stale entry.
This is not a general-purpose cache. Values are strong. If a value points back at its key, the key is still reachable through the map: value → key, and the weak key never clears. That leak is common. Store values that do not refer to the key, or wrap values in WeakReference yourself (and then you want a different design).
Keys are compared with == identity after the weak wrap, via the usual equals/hashCode of the key object while it lives. Identity of interned strings makes String keys a poor fit: literals stay alive forever. Use keys whose lifetime you actually control.
The map is not thread-safe. Size can shrink between calls after a GC. null keys are allowed (one). Iteration can see entries vanish. Do not depend on a key remaining after you drop it.
You reach for WeakHashMap when you want attached metadata that should die with the object: a listener list, a computed property, an identity-based side table. You reach for WeakReference / SoftReference caches with explicit eviction when you care about memory pressure. Soft references clear on memory pressure; weak references clear at the next GC after the key is only weakly reachable. WeakHashMap is weak, not soft.
The cost of treating it as HashMap is disappearing keys in tests that trigger GC, and a leak if values retain keys. The cost of using it as an unbounded cache of values that keep the world alive is the same leak you tried to avoid. Prefer Caffeine or a bounded LinkedHashMap for real caches.
Code Examples
import java.util.WeakHashMap;
public class Meta {
public static void main(String[] args) {
WeakHashMap<Object, String> meta = new WeakHashMap<>();
Object key = new Object();
meta.put(key, "payload");
System.out.println(meta.get(key)); // prints: payload
key = null; // last strong ref dropped; GC may now collect the entry
System.gc();
System.out.println(meta.size() >= 0); // prints: true (size may be 0 or 1)
}
}import java.util.WeakHashMap;
public class NoStringKeys {
public static void main(String[] args) {
WeakHashMap<String, Integer> map = new WeakHashMap<>();
map.put("literal", 1); // interned; likely never collected
System.out.println(map.get("literal")); // prints: 1
}
}Common Gotchas
A value that references its key pins the key
the weak key never clears. Do not store the key inside the value.
String literals and interned keys never go away
use ephemeral identity keys.
`System.gc()` is only a hint
tests that assert a collected entry are flaky.
Not a bounded cache and not thread-safe
writers still need external sync.