WeakHashMap
A WeakHashMap holds its keys weakly: when nothing else refers to a key, the garbage collector may remove it, and the entry disappears from the map. That makes it useful for attaching data to objects without keeping them alive, and surprising in almost every other use. This page explains the reference mechanism underneath, shows entries vanishing, and runs the traps with string keys, small integers and values that point at their keys.
Contents
Weak references and how WeakHashMap uses them
Normally, an object stays alive as long as any variable, field or collection refers to it: those are strong references. The java.lang.ref
- A
does not keep its object alive. Once only weak references remain, the next garbage collection may clear them and reclaim the object.WeakReference - A
is cleared only when the JVM is running short of memory, which makes it suited to memory-sensitive caches.SoftReference - A
receives references after their objects have been cleared, so code can find out and clean up.ReferenceQueue
WeakHashMapsizegetputequalshashCodeHashMap
| Tool | Since | Cleared when | Best for |
|---|---|---|---|
WeakHashMap | Java 1.2 | The key is only weakly reachable | Extra data attached to objects you do not own |
WeakReference | Java 1.2 | At the next collection after it is weakly reachable | Listeners and canonical instances |
SoftReference | Java 1.2 | Memory is short | Simple caches of reloadable data |
ReferenceQueue | Java 1.2 | Receives cleared references | Cleaning up after collection |
java.lang.ref.Cleaner | Java 9 | Runs an action after the object is unreachable | Releasing native resources; replaces finalize |
The programs on this page call System.gc()
Entries disappear when keys become unreachable
The same keys go into a HashMapWeakHashMap
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
public class WeakKeys {
static class Session {
final String id;
Session(String id) {
this.id = id;
}
@Override
public String toString() {
return id;
}
}
public static void main(String[] args) throws InterruptedException {
Map<Session, String> strong = new HashMap<>();
Map<Session, String> weak = new WeakHashMap<>();
Session s1 = new Session("s1");
Session s2 = new Session("s2");
strong.put(s1, "data");
strong.put(s2, "data");
weak.put(new Session("w1"), "data");
weak.put(new Session("w2"), "data");
Session kept = new Session("w3");
weak.put(kept, "data");
s1 = null; // the HashMap itself still references the key
s2 = null;
for (int i = 0; i < 10 && weak.size() > 1; i++) {
System.gc(); // a request, not a guarantee, so retry a few times
Thread.sleep(50);
}
System.out.println("HashMap size: " + strong.size());
System.out.println("WeakHashMap size: " + weak.size() + " " + weak.keySet());
System.out.println("kept is still referenced: " + kept);
}
}
Output:
HashMap size: 2
WeakHashMap size: 1 [w3]
kept is still referenced: w3
- The
still held both entries: its strong references alone keep the keys alive, which is how ordinary maps cause memory leaks when entries are never removed.HashMap - The
kept onlyWeakHashMap , the key the program still refers to. The other entry was removed after its key was collected.w3 - When an entry disappears depends on the garbage collector, so code must never rely on a
entry still being there, or being gone, at any particular moment.WeakHashMap
The String and Integer key trap
Some objects are never collected while the program runs, because the JVM itself keeps them reachable. The program uses two such keys, a small Integer
import java.util.Map;
import java.util.WeakHashMap;
public class StringKeyTrap {
public static void main(String[] args) throws InterruptedException {
Map<Object, String> weak = new WeakHashMap<>();
weak.put("literal", "interned string: lives as long as the class");
weak.put(42, "small Integer: cached by Integer.valueOf");
weak.put(new String("built at runtime"), "ordinary object");
for (int i = 0; i < 10 && weak.size() > 2; i++) {
System.gc();
Thread.sleep(50);
}
weak.forEach((k, v) -> System.out.println("still present: " + k + " (" + v + ")"));
}
}
Output:
still present: 42 (small Integer: cached by Integer.valueOf)
still present: literal (interned string: lives as long as the class)
caches the values from -128 to 127, and autoboxing uses that cache, so the key 42 is referenced by the cache forever.Integer.valueOf- A string literal is held by the class that uses it, as explained on the
string pool page , so it lives as long as the class. - Both entries stayed after garbage collection. A
with string or number keys usually behaves like aWeakHashMap that leaks or, with strings built at run time, like one that loses entries at random. Its keys should be objects whose lifetime you care about, such as sessions, class loaders or UI components.HashMap
The value that pins its key
Values are strongly referenced from the map. The program stores a value that refers back to its own key and then drops every other reference.
import java.util.Map;
import java.util.WeakHashMap;
public class ValueTrap {
record Holder(Object owner) {
}
public static void main(String[] args) throws InterruptedException {
Map<Object, Object> weak = new WeakHashMap<>();
Object key = new Object();
weak.put(key, new Holder(key)); // the value points back at its own key
key = null;
for (int i = 0; i < 10; i++) {
System.gc();
Thread.sleep(50);
}
// Values are held strongly, so the key stays reachable through its own value
System.out.println("entries after GC: " + weak.size());
}
}
Output:
entries after GC: 1
The entry was still there after repeated collections. The map holds the value strongly, the value holds the key strongly, so the key is never only weakly reachable and is never cleared. The WeakHashMapWeakReference
The reference mechanism underneath
The last program uses the building blocks directly: a weak reference with a queue, a soft reference, and a WeakHashMap
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.WeakHashMap;
public class References {
static final class Key {
final String id;
Key(String id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
return o instanceof Key k && k.id.equals(id);
}
@Override
public int hashCode() {
return id.hashCode();
}
}
public static void main(String[] args) throws InterruptedException {
// WeakReference and a ReferenceQueue: the mechanism inside WeakHashMap
ReferenceQueue<Object> queue = new ReferenceQueue<>();
Object payload = new Object();
WeakReference<Object> weak = new WeakReference<>(payload, queue);
SoftReference<byte[]> soft = new SoftReference<>(new byte[1024]);
payload = null; // drop the only strong reference
System.gc();
Reference<?> enqueued = queue.remove(1000); // wait up to 1 s
System.out.println("weak.get() after GC: " + weak.get());
System.out.println("enqueued in the queue: " + (enqueued == weak));
System.out.println("soft.get() after GC: " + (soft.get() != null
? "still there (soft references survive until memory is short)" : "cleared"));
// WeakHashMap compares keys with equals, not identity
Map<Key, String> meta = new WeakHashMap<>();
Key k1 = new Key("a");
meta.put(k1, "first");
meta.put(new Key("a"), "second"); // equal key: replaces the value
System.out.println("equal keys share an entry: " + meta.size() + " entry, value "
+ meta.get(k1));
Reference.reachabilityFence(k1); // keep k1 strongly reachable until here
}
}
Output:
weak.get() after GC: null
enqueued in the queue: true
soft.get() after GC: still there (soft references survive until memory is short)
equal keys share an entry: 1 entry, value second
- After its only strong reference was dropped and garbage collection ran, the weak reference returned
, and the same reference object appeared in the queue.null polls such a queue to find entries to remove.WeakHashMap - The soft reference survived the collection, because memory was not short. That makes soft references unpredictable for caches: they hold data until the heap is almost full, then many are cleared at once.
- Two distinct
objects with equal ids share one entry, becauseKey usesWeakHashMap . For identity semantics there is no weak identity map in the JDK; libraries such as Guava'sequals provide one.MapMaker (Java 9) keeps a variable strongly reachable up to that point, since the JIT may otherwise treat a variable as dead after its last use.Reference.reachabilityFence
A side table that does not leak
The main job of a WeakHashMapHashMapWeakHashMap
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
public class SideTable {
// A class we do not own and cannot add a field to
static final class Request {
final int id;
Request(int id) {
this.id = id;
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("attach 1 KB of metadata to each of 100,000 short-lived requests");
run("HashMap", new HashMap<>());
run("WeakHashMap", new WeakHashMap<>());
}
static void run(String name, Map<Request, byte[]> metadata) throws InterruptedException {
long before = usedMb();
for (int i = 0; i < 100000; i++) {
Request r = new Request(i);
metadata.put(r, new byte[1024]); // the request itself is dropped right after this
}
long after = usedMb();
System.out.printf(" %-12s entries left %,7d, heap grew by about %3d MB%n", name,
metadata.size(), after - before);
}
static long usedMb() throws InterruptedException {
Runtime rt = Runtime.getRuntime();
for (int i = 0; i < 3; i++) {
System.gc();
Thread.sleep(50);
}
return (rt.totalMemory() - rt.freeMemory()) >> 20;
}
}
Output (JDK 21, default G1 collector; heap figures after System.gc()
attach 1 KB of metadata to each of 100,000 short-lived requests
HashMap entries left 100,000, heap grew by about 106 MB
WeakHashMap entries left 0, heap grew by about 41 MB
- The
kept all 100,000 entries and about 100 MB of metadata for requests nobody used any more. In a server, that map grows with every request until the JVM runs out of memory.HashMap - The
had 0 entries left. Each request became unreachable as soon as its loop iteration ended, so its weak reference was cleared and its entry was removed on the next call to the map.WeakHashMap - Its heap growth was well below the
's but not zero, and it varied from about a sixth to under half of it between runs. Removing an entry makes its 1 KB value unreachable, but the collector frees that memory in a later cycle, so a heap reading taken straight after the removals still counts some of it.HashMap - The map also keeps its grown bucket array. Like a
, it enlarges the table while entries are added and never shrinks it when they go.HashMap - When the data belongs to a class rather than to individual objects,
(Java 7) is the better side table. It computes a value once perClassValue and lets class loaders be unloaded, which aClass keyed byWeakHashMap cannot promise if a value refers back to its class.Class
Traps: a map that changes by itself, and Cleaner
Because the garbage collector removes entries, a WeakHashMapCleaner
import java.lang.ref.Cleaner;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class ChangingUnderYou {
static final Cleaner CLEANER = Cleaner.create();
public static void main(String[] args) throws InterruptedException {
// 1. The map shrinks although no code calls remove
Map<Object, String> map = new WeakHashMap<>();
Object keep = new Object();
map.put(keep, "kept");
for (int i = 0; i < 1000; i++) {
map.put(new Object(), "temp " + i);
}
int first = map.size();
boolean emptyBefore = map.isEmpty();
for (int i = 0; i < 5 && map.size() > 1; i++) {
System.gc();
Thread.sleep(50);
}
System.out.println("size " + first + ", later " + map.size()
+ " with no remove call; isEmpty was " + emptyBefore + " and stays " + map.isEmpty());
// 2. Values loaded before a check can vanish after it
Object key = new Object();
map.put(key, "session data");
boolean present = map.containsKey(key);
key = null;
for (int i = 0; i < 5 && map.size() > 1; i++) {
System.gc();
Thread.sleep(50);
}
System.out.println("containsKey said " + present + "; entries now " + map.size()
+ ", so check and use in one step: get() and test for null");
// 3. Cleaner (Java 9) runs an action after an object becomes unreachable
CountDownLatch done = new CountDownLatch(1);
Object resource = new Object();
CLEANER.register(resource, () -> {
System.out.println("cleaner action ran on its own thread: "
+ Thread.currentThread().getName());
done.countDown();
});
resource = null;
boolean ran = false;
for (int i = 0; i < 10 && !ran; i++) {
System.gc();
ran = done.await(100, TimeUnit.MILLISECONDS);
}
System.out.println("cleanup finished: " + ran + "; the kept key still maps to "
+ map.get(keep));
}
}
size 1001, later 1 with no remove call; isEmpty was false and stays false
containsKey said true; entries now 1, so check and use in one step: get() and test for null
cleaner action ran on its own thread: Cleaner-0
cleanup finished: true; the kept key still maps to kept
- The size fell from 1,001 to 1 with no call to
. Stale entries are removed inside the map's own methods, by a privateremove step thatexpungeStaleEntries ,size andget run first. Code that stores a size, or iterates while assuming entries stay put, can see different answers from one call to the next.put returned true, and then the entry disappeared once its key was dropped and a collection ran. A check followed by a separatecontainsKey can therefore find nothing. Callget once, keep the result in a local variable, and test that forget .null- The
action ran on the cleaner's own thread,Cleaner , after the registered object became unreachable. The action must not refer to that object, or it would keep it alive, the same trap as a value that refers to its key.Cleaner-0 - The kept key still mapped to
throughout, because the program held a strong reference to it.kept
WeakHashMapCollections.synchronizedMap
When to use WeakHashMap
| Situation | Use |
|---|---|
| Attach data to objects you do not own, without keeping them alive | WeakHashMap<TheirObject, Data> |
| Cache with size limits or expiry | A caching library such as Caffeine, or an LRU LinkedHashMap |
| Keys are strings, numbers or enums | A normal map; weak keys do not help |
| Listeners that should not keep their owners alive | A list of WeakReference |
| Free native resources when an object dies | Cleaner |
| Shared between threads | Collections.synchronizedMap(new WeakHashMap<>()) |
| A value that refers to its key | Wrap that reference in a WeakReference |
An LRU cache with LinkedHashMap