Video in progress

Strong Middle 🧺 Collections

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:

  1. 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.

  1. The key is always alive. String literals, small Integers, enums: they live in a pool or cache. Putting a literal key into a WeakHashMap<String, ...> makes no sense.

  2. Keys compared by equals. WeakHashMap uses equals/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.