Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

How does WeakHashMap decide when to remove an entry, and name two ways it surprises people.

WeakHashMap holds its keys through weak references, so once nothing else in the program refers to a key strongly, the garbage collector may clear that reference and queue it. The map then removes the entry the next time we call a method such as get, put or size, not at the moment of collection. It surprises people in two common ways: an entry whose value refers to its own key is never removed, and keys such as string literals that stay reachable elsewhere are never collected at all.

Why this question is asked

WeakHashMap looks like a free memory-management tool, and that is why it is misused so often. Developers reach for it to build caches or listener registries and then find entries that vanish too early or never vanish at all. Interviewers ask this question to see whether we understand reachability and weak references, rather than thinking of WeakHashMap as a map that cleans itself up. In this answer, we will recap what a weak reference is, follow how WeakHashMap removes an entry step by step, and then reproduce the two classic surprises and a third practical one.

1A Quick Recap of Weak References

The garbage collector frees an object only when the program can no longer reach it. Normally we hold objects through strong references, ordinary fields and variables, and as long as one strong path leads to an object, it stays alive.

A WeakReference is a special object from java.lang.ref that points to another object without keeping it alive. If the only paths to an object go through weak references, the object is called weakly reachable, and the collector is free to reclaim it. When it does, it clears the weak reference, so get() on it returns null, and if the reference was created with a ReferenceQueue, it puts the cleared reference on that queue so the program can learn about it.

2How WeakHashMap Removes an Entry

WeakHashMap is a hash map whose entries extend WeakReference. Each entry refers to its key weakly and to its value strongly, and every entry is registered with the map's own ReferenceQueue. Lookups use equals and hashCode just like HashMap.

Java
Map<Object, String> map = new WeakHashMap<>();
Object key = new Object();
map.put(key, "metadata");
map.size(); // 1
key = null; // drop the only strong reference
System.gc(); // a hint; the collector may now clear the weak reference
Thread.sleep(100);
map.size(); // usually 0: size() expunged the cleared entry first
Step throughFrom last strong reference to removed entry
  1. Program drops the last strong reference to the key
  2. Key is now only weakly reachable
  3. GC runs and decides to reclaim the keytiming depends on memory pressure
  4. GC clears the weak reference and enqueues the entry
  5. Next get, put or size on the map
  6. expungeStaleEntries unlinks the entrythe value becomes collectable too

6 steps in order. Play them, or step through them one at a time.

Nothing happens to the map itself until we call one of its methods.

Notice the order of events. The collector does not touch the map. It only clears the weak reference inside the entry and enqueues it. The entry object is still in the bucket array. The next time we call almost any method on the map, such as get, put, size or iteration, WeakHashMap first runs a private method called expungeStaleEntries, which polls its queue and unlinks each entry that was cleared. So removal is lazy and happens on our thread, during our next operation. A map that nobody touches keeps its dead entries and their values in memory indefinitely.

3Surprise 1: A Value That Refers to Its Key

The value is held strongly by the entry, and the entry is held strongly by the map. If the value contains a reference back to its key, the key is always strongly reachable through the map itself, so it never becomes weakly reachable and the entry is never removed.

Java
record Session(User owner, Instant started) {}
Map<User, Session> sessions = new WeakHashMap<>();
User u = new User("alice");
sessions.put(u, new Session(u, Instant.now())); // the value points back to the key
u = null;
System.gc();
sessions.size(); // still 1, forever: map -> entry -> value -> key

This is a memory leak that looks like correct code. The Javadoc of WeakHashMap warns about it. The fix is to make sure values do not refer to keys strongly, or to wrap such a value in a WeakReference itself, and accept that it can then be cleared.

4Surprise 2: Keys That Never Die

WeakHashMap only removes an entry when its key object becomes unreachable. Some keys are kept alive by something else for the life of the program. String literals and interned strings are held by the JVM's string pool, small boxed Integers from -128 to 127 are held by the Integer cache, and enum constants and Class objects of the application stay alive as long as their class loader.

Java
Map<String, byte[]> map = new WeakHashMap<>();
map.put("report", new byte[10_000_000]); // literal key, interned by the JVM
System.gc();
map.size(); // 1: the literal is always strongly reachable

The opposite surprise follows from the same rule. Because WeakHashMap uses equals, we can look up an entry with a different but equal key object. But only the original key object decides the entry's lifetime. If we put with new String("id") and later get with another equal string, the entry still disappears once the first string becomes unreachable, even though we can still create equal keys.

5It Is Not Thread-Safe

WeakHashMap has no internal locking, and the hidden expunging means that even a get() modifies the internal structure. So two threads that only read can still corrupt it. If we share one between threads, we wrap it with Collections.synchronizedMap and accept the lock on every call, or we choose a library that offers concurrent weak-keyed maps, such as Caffeine's weakKeys() option.

6Follow-up questions

How would you build a map with weak values instead?

WeakHashMap only makes keys weak. For weak values, we store WeakReference<V> as the value, register each reference with a ReferenceQueue, and periodically poll the queue to remove entries whose value was cleared; a small subclass of WeakReference that also remembers its key makes the removal easy. In practice, Caffeine offers weakValues() and softValues() and does this bookkeeping for us, so we would use it rather than writing our own.

Does System.gc() guarantee that the entry disappears?

No. System.gc() is only a hint, and the collector decides which objects it reclaims and when. Code that relies on entries disappearing at a particular moment is fragile. Tests that check WeakHashMap behaviour usually loop with a timeout, calling System.gc() and checking the size until it drops.

What is the difference between a weak and a soft reference?

A weakly reachable object can be reclaimed at the next collection. A softly reachable object is kept until the JVM needs memory, so soft references were once used for caches. Modern guidance avoids soft-reference caches too, because they make GC behaviour unpredictable under pressure, and prefers caches with explicit size limits.

7Conclusion

In this answer, we saw that WeakHashMap keeps keys through weak references and values through strong ones. When a key becomes only weakly reachable, the collector may clear and enqueue its reference, and the map removes the entry lazily on the next operation such as get, put or size. Values that refer back to their keys keep entries alive forever, keys held elsewhere, such as interned strings, are never collected, and the map is not thread-safe, even for reads.

What to say in the interviewAbout 80 seconds aloud

Open with

WeakHashMap stores each entry as a weak reference to the key and a strong reference to the value. When the program drops its last strong reference to a key, the key becomes weakly reachable, and at some later collection the GC may clear that reference and put it on the map's reference queue.

Then, if they want more

The map does not change at that moment. The next time I call get, put, size or iterate, it runs expungeStaleEntries, polls the queue and unlinks the cleared entries. So removal is lazy, and a map that nobody touches keeps its stale values.

The first surprise is that the value is strongly held, so if the value refers back to its key, for example a Session that holds its User, the key is always reachable through the map and the entry is never removed.

The second is that it uses equals and hashCode, but lifetime depends on the key object itself, so string literals, interned strings or cached small Integers as keys are effectively never collected. I would also mention that it is not thread-safe, and even get mutates it because of the expunging. For weak values, I would use Caffeine's weakValues rather than build it myself.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How does WeakHashMap decide when to remove an entry, and name two ways it surprises...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/e993a9ee62/