WeakHashMap — Garbage Collection-Friendly Cache
Fast recall
Quick revision
Core answer
Understanding of Java reference types (strong, weak, soft) and how WeakHashMap prevents memory leaks in cache-like structures
Using WeakHashMap as a general-purpose cache without understanding that entries can be removed at any time by the GC, or that values (not keys) hold strong references which can prevent key GC if not careful
Contrast with SoftReference-based caches (Guava's CacheBuilder with softValues) which are evicted only under memory pressure — more suitable than WeakHashMap for caches. Also mention that WeakHashMap is not thread-safe; use Collections.synchronizedMap to wrap it.
Interview-ready guide
Interview answer
WeakHashMap stores keys as weak references — when a key has no strong references elsewhere in the application, the GC collects it and the entry disappears automatically.
How cleanup works:
- Entries are expunged lazily during the next map operation by polling a ReferenceQueue
- If the map is never accessed, stale entries accumulate without being cleaned
Common mistake — using it as a cache:
- WeakHashMap evicts based on key reachability, not memory pressure
- A key with no strong references is collected on the next GC even when the JVM has gigabytes of free heap
- For caching, use
SoftReference— retained until the JVM actually needs the memory
Retain cycle trap:
- Values are strong references — if a value holds a reference back to its key, the key can never be collected
- This silently defeats the entire weak reference semantics; the entry never disappears
I recommend WeakHashMap for canonicalization maps and attaching metadata to objects that should auto-remove when the subject is no longer in use. For caching, it is almost always the wrong choice.
WeakHashMap — Garbage Collection-Friendly Cache
Direct Answer
WeakHashMap stores keys as WeakReferences. When a key has no strong references elsewhere, the GC can collect it and the entry is automatically removed from the map. It is useful for metadata caches keyed on live objects, preventing memory leaks when the key object is no longer used.
Deep Dive & Architecture
compute, merge, computeIfAbsent, and computeIfPresent are Map methods (Java 8+) that atomically combine get + check + put into a single operation, replacing the verbose get-check-put anti-pattern. computeIfAbsent(key, mappingFunction) — if key absent, compute value and put; most-used for lazy initialization of multi-valued maps: map.computeIfAbsent(key, k -> new ArrayList<>()).add(value). computeIfPresent(key, remappingFunction) — if key present, recompute value (or remove if null returned). compute(key, remappingFunction) — recompute regardless of presence (function gets old value or null). merge(key, value, remappingFunction) — if absent, put value; if present, apply function to combine: map.merge(word, 1, Integer::sum) is the idiomatic word-counter. Why they matter: (1) atomic in ConcurrentHashMap — no lost updates from concurrent get-check-put races; (2) less code than if (map.containsKey(k)) map.put(k, ...) else map.put(k, ...); (3) cleaner intent — the operation says what it does. Pitfalls: (1) not atomic in non-concurrent maps (HashMap) — only the API is single-call, not thread-safe; (2) returning null from a remapping function removes the key — surprising; (3) don't recursively modify the map inside the function — undefined behavior; (4) merge doesn't handle null values the same way as compute — read the Javadoc. For interviews: lead with 'replaces get-check-put, atomic in ConcurrentHashMap, idiomatic for multimap lazy-init and counters'.
WeakHashMap stores keys as WeakReferences. When a key has no strong references elsewhere, the GC can collect it and the entry is automatically removed from the map. It is useful for metadata caches keyed on live objects, preventing memory leaks when the key object is no longer used.
A common mistake is confusing the interface with the implementation (e.g., saying List when you mean ArrayList), or not knowing that Map does not extend Collection.
Common Mistakes & Pitfalls
Using WeakHashMap as a general-purpose cache without understanding that entries can be removed at any time by the GC, or that values (not keys) hold strong references which can prevent key GC if not careful
Check your understanding
Answer these without looking back at the article.
- What is the Java Collections Framework (JCF) and why does it exist? It provides a unified architecture of interfaces and implementations for storing and manipulating groups of objects, replacing the ad-hoc pre-JCF classes (Vector, Hashtable, Enumeration) with a consistent, interoperable API.
- How does HashSet work internally in Java?
- How does HashMap internally handle hash collisions in Java 8+? Explain the transition from linked list to tree.
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.