Video in progress

Strong Junior ⚙️ JVM and memory

How does WeakHashMap work, and why is using it as a cache often a mistake?

WeakHashMap holds keys through weak references: if no other strong reference to the key remains, the GC collects it and the entry disappears from the map on its own. But the cleanup depends on whether the key is alive, not the value, so it is not an ordinary cache that "gets cleaned when memory runs low".

📖 Answer

In Java there are several strengths of references:

  • strong: an ordinary reference, the object is alive;
  • soft (SoftReference): the GC may collect it when memory is tight;
  • weak (WeakReference): collected at the next GC if there is no strong reference;
  • phantom: only to learn that an object has been collected.

Where WeakHashMap fits: "attaching" extra data to an object so that the data goes away when the object dies. For example, metadata tied to a Thread or a ClassLoader.

The traps as a cache:

Map<String, Report> cache = new WeakHashMap<>();
cache.put(new String("2024-Q1"), report);   // no other reference to the key
// after the next GC the entry may disappear
  • String literal keys live in the string pool and are never collected, so entries stay forever;
  • if the value references the key, the key never "dies" and you get a leak;
  • lookup is by equals, but cleanup depends on identity, which is confusing;
  • it is not thread-safe.

If you need a cache, use Caffeine: size, TTL and, if needed, weakKeys()/softValues() in one place.