What is WeakHashMap, what makes its keys garbage-collectible, and what is a common use for it?
answer
- Keys via WeakReference -> GC can reclaim them
- Values are STRONG (value->key ref pins the entry)
- Cleanup is lazy via ReferenceQueue on map access
- Use: metadata/caches that must not keep objects alive
- Non-deterministic timing; not thread-safe
basics
~20 sWeakHashMap holds its keys with weak references, so once nothing else strongly points to a key, the garbage collector can remove it and its entry disappears automatically. It suits metadata or caches keyed by objects they should not keep alive.
solid answer
~50 sWeakHashMap is a Map whose keys are held via WeakReference. A weak reference does not stop the garbage collector from reclaiming an object: if the only thing referencing a key is the WeakHashMap itself, the GC can collect that key, and the map then drops the corresponding entry automatically (lazily, as you touch the map, via a ReferenceQueue). This suits auxiliary metadata or caches that must not keep their keys alive — e.g. associating extra data with objects without causing memory leaks. Two gotchas: a key you don't retain, like new String("id"), can vanish though an equal key can be rebuilt, which is why the Javadoc aims the class at identity-equals keys; a key the JVM keeps reachable, like a String literal or cached boxed Integer, may never go. Note: only keys are weak; values are strong, so a value that references its own key can pin the entry (preventing collection). It is not thread-safe.
code
java · 12 linesWeakHashMap<Object, String> map = new WeakHashMap<>();
Object key = new Object();
map.put(key, "metadata");
System.out.println(map.size()); // 1
key = null; // remove the only strong reference
System.gc(); // hint the collector
// timing is non-deterministic; after GC + a map access:
System.out.println(map.size()); // may print 0
// LEAK TRAP: value strongly references its own key ->
// the key stays strongly reachable, and the entry stays while the map lives.go deeper
Knows WeakHashMap keys can be garbage-collected when nothing else references them, useful to avoid leaks.
Explains weak vs strong references, that the GC reclaims weakly-held keys and the map drops the entry, and a basic cache/metadata use case.
Explains the ReferenceQueue/lazy expunge mechanism, that only keys are weak (value->key pinning leak), non-deterministic timing, and the string-literal/boxed-Integer pitfalls.
Reasons about WeakHashMap vs soft references vs a real cache, framework use (ThreadLocalMap-style), memory-leak diagnosis, GC interaction/visibility, and why deterministic resource cleanup needs a different tool.
## Reference strength in Java The garbage collector (GC) reclaims objects that are no longer **reachable**. But not all references are equal: - **Strong reference** (`Object o = ...;`): the normal kind. As long as a strong reference exists, the object is reachable and **cannot** be collected. - **Weak reference** (`WeakReference<T>`): a special wrapper. If the *only* references to an object are weak, the GC is **free to reclaim it**. After collection, the weak reference's `get()` returns `null`. (There are also soft and phantom references, but weak is what matters here.) ## What WeakHashMap does `WeakHashMap` is a hash map that stores each **key inside a `WeakReference`** (specifically a subclass tied to a `ReferenceQueue`). The **values are held strongly**. The effect: > If no strong or soft reference to a key exists anywhere else in your program, the GC may collect that key. The map then **automatically removes** the now-dead entry. This cleanup is **lazy**: the map doesn't get a callback the instant the GC runs. Instead, the GC enqueues the cleared weak references onto a `ReferenceQueue`; the next time you call a method like `size()`, `get()`, or iterate, the map drains that queue (its `expungeStaleEntries()` step) and removes the dead entries. So `size()` can shrink over time even though you never called `remove()`. ``` WeakHashMap<Object,String> m = new WeakHashMap<>(); Object key = new Object(); m.put(key, "meta"); // entry present key = null; // drop the only strong ref System.gc(); // GC may now reclaim the key // after some map access, m.size() can become 0 ``` ## Why this is useful — canonical use cases 1. **Attaching metadata to objects without owning their lifecycle.** You want to associate extra info with objects you don't control, but you must **not** keep them alive. WeakHashMap lets the entry die when the object dies, so the map itself causes no leak unless a value refers back to its key. `ThreadLocal`'s internal `ThreadLocalMap` applies the same idea with its own weak-keyed table, not with this class. 2. **Caches that should evict naturally.** A cache keyed by objects that the rest of the app still uses; when the app stops using an object, its cache entry can go too. (For value-driven caches, you usually want a real cache library or soft references instead.) 3. **Canonicalizing maps / listener registries** that shouldn't prevent the registered objects from being collected. In a canonicalizing map whose value refers to its key, the entry pins itself; wrapping the value in a `WeakReference` avoids that only if nothing relies on the map to keep the value alive. ## The big gotchas - **Only keys are weak; values are strong.** If a *value* (or anything the value references) holds a strong reference back to its **key**, the key cannot become weakly-reachable while the map is alive, so the entry stays — a silent leak. The path can be indirect, through another entry's key and value. Fix: restructure, or wrap such values in a `WeakReference` if nothing relies on the map to keep them alive. - **Recreatable keys confuse.** Lookups use `equals`, yet the Javadoc says the class is "intended primarily for use with key objects whose `equals` methods test for object identity". Put `new String("id")` without retaining it and, after a GC, `get("id")` returns null although you can build an equal key at will. - **Keys the JVM keeps reachable stay.** A **string literal** stays reachable while its class is loaded, and a **cached boxed value** (`Integer.valueOf(1)`) through the cache, so entries keyed on them may **never** disappear. A string interned at run time is not pinned that way: HotSpot's string table holds it weakly, and that entry can disappear. Since JDK 25 `javac` warns about the boxed case: `WeakHashMap<Integer, String>` draws `[identity] use of a value-based class with an operation that expects reliable identity`. - **The null key** is supported and, stored as a static sentinel, is never collected. - **Non-deterministic timing.** You cannot predict *when* entries disappear; it depends on GC. Don't rely on WeakHashMap for correctness that needs deterministic removal. - **Not thread-safe.** Wrap with `Collections.synchronizedMap` if shared. ## Mental model A normal `HashMap` is a strong owner: it keeps every key alive until you `remove` it or drop the map. `WeakHashMap` is a *non-owning observer*: once nobody *else* holds a key, it may quietly forget it at any later GC.
- Why might a WeakHashMap entry never get collected even after you drop your reference to the key?Because something still holds a strong reference to the key. A common cause is the entry's own value (held strongly) referencing the key directly or transitively, pinning it. String literals and cached boxed integers also stay reachable through the JVM.
- When exactly are dead entries removed from a WeakHashMap?Lazily. The GC enqueues cleared key references onto a ReferenceQueue; the map drains that queue and expunges stale entries during subsequent operations (size, get, put, iteration). There is no immediate callback, so removal timing is non-deterministic.
WeakHashMap is a coat-check that only keeps your ticket while you still hold the coat. The moment you let go of the coat (no strong reference), the attendant is allowed to throw out your ticket too.
- Saying values are also weak — only keys are weak; values are strong.
- Relying on deterministic/immediate removal of entries.
- Keying on a String literal and expecting its entry to be collected.
- Using it as a thread-safe cache without synchronization.
- Not realizing a value->key strong reference pins the entry (leak).
- Expecting an equal key to find an entry after the original key instance was collected.
- WeakHashMap
- Java 1.2
- java.lang.ref.WeakReference
- Java 1.2
Assumes JDK 27; WeakHashMap.java has no code difference at JDK 25. javac's identity warning on a value-based key type, such as WeakHashMap<Integer, String>, appears on both 25 and 27.
context
- WeakHashMap (Java SE 27 & JDK 27)docs.oracle.com
- java.lang.ref (Java SE 27 & JDK 27)docs.oracle.com
- WeakHashMap.java at jdk-27-gagithub.com