Video in progress
How does WeakHashMap work, and when can't it stop a memory leak?
WeakHashMap holds keys through weak references: if no strong reference to the key remains anywhere else, the GC collects it and the entry disappears from the map on the next access. But the value is held by a strong reference, so if the value references its own key, the entry never goes away.
📖 Answer
The idea: attach "extra data" to an object without extending the object's lifetime.
Map<Session, Metrics> extra = new WeakHashMap<>();
extra.put(session, new Metrics());
// once session is no longer used anywhere else, the entry disappears after GC too
Cases where it doesn't work:
- The value holds the key.
extra.put(session, new Metrics(session)); // Metrics has a session field
Map → value → key: there is a strong path to the key, so it will never be collected.
-
The key is always alive.
Stringliterals, smallIntegers, enums: they live in a pool or cache. Putting a literal key into aWeakHashMap<String, ...>makes no sense. -
Keys compared by
equals.WeakHashMapusesequals/hashCode. If you need object identity, this gives unexpected results.
Cleanup depends on the GC and only happens when the map is accessed (get, put, size), so its timing is unpredictable. That is why I don't use it as a cache: for a cache, a solution with a bounded size and TTL (Caffeine, which also has weakKeys() if you need it) is more predictable.
Sign up to mark studied questions and save your progress.