java.util · java.base · since Java 1.2

WeakHashMap

declaration
public class WeakHashMap<K, V> extends AbstractMap<K, V>

Map whose entries vanish when the key becomes weakly reachable — canonicalizing caches keyed by objects with external lifetimes.

  • Entries disappear at GC discretion — size() is advisory
  • Values holding strong references back to their keys defeat the mechanism

Key methods

static <K,V> WeakHashMap<K,V> newWeakHashMap(int numMappings)Correctly presized factory (Java 19+).