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 package, available since Java 1.2, adds weaker kinds:

  • A WeakReference does not keep its object alive. Once only weak references remain, the next garbage collection may clear them and reclaim the object.
  • A SoftReference is cleared only when the JVM is running short of memory, which makes it suited to memory-sensitive caches.
  • A ReferenceQueue receives references after their objects have been cleared, so code can find out and clean up.

WeakHashMap (Java 1.2) wraps each key in a weak reference registered with an internal queue. When a key is collected, its reference lands in the queue, and the next call on the map, such as size, get or put, removes the stale entries. Values are held strongly, which matters for one of the traps below. Keys are compared with equals and hashCode, like a HashMap.

Reference-based tools
ToolSinceCleared whenBest for
WeakHashMapJava 1.2The key is only weakly reachableExtra data attached to objects you do not own
WeakReferenceJava 1.2At the next collection after it is weakly reachableListeners and canonical instances
SoftReferenceJava 1.2Memory is shortSimple caches of reloadable data
ReferenceQueueJava 1.2Receives cleared referencesCleaning up after collection
java.lang.ref.CleanerJava 9Runs an action after the object is unreachableReleasing native resources; replaces finalize

The programs on this page call System.gc(), which is only a request; they retry a few times so that the collection actually happens. They ran on JDK 21 with the default G1 collector, and other JVMs or settings may time collection differently.

Entries disappear when keys become unreachable

The same keys go into a HashMap and a WeakHashMap; then the program drops its own references to all keys but one and asks for garbage collection.

Java
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:

Output
HashMap size:     2
WeakHashMap size: 1 [w3]
kept is still referenced: w3
  • The HashMap 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.
  • The WeakHashMap kept only w3, the key the program still refers to. The other entry was removed after its key was collected.
  • When an entry disappears depends on the garbage collector, so code must never rely on a WeakHashMap entry still being there, or being gone, at any particular moment.

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 and a string literal.

Java
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:

Output
still present: 42  (small Integer: cached by Integer.valueOf)
still present: literal  (interned string: lives as long as the class)
  • Integer.valueOf caches the values from -128 to 127, and autoboxing uses that cache, so the key 42 is referenced by the cache forever.
  • 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 WeakHashMap with string or number keys usually behaves like a HashMap 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.

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.

Java
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:

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 WeakHashMap documentation warns about exactly this. If a value must refer to its key, wrap the value's reference in a WeakReference, or redesign so the value does not need it.

The reference mechanism underneath

The last program uses the building blocks directly: a weak reference with a queue, a soft reference, and a WeakHashMap with two equal keys.

Java
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:

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 null, and the same reference object appeared in the queue. WeakHashMap polls such a queue to find entries to remove.
  • 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 Key objects with equal ids share one entry, because WeakHashMap uses equals. For identity semantics there is no weak identity map in the JDK; libraries such as Guava's MapMaker provide one.
  • Reference.reachabilityFence (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.

A side table that does not leak

The main job of a WeakHashMap is a side table: extra data attached to objects you do not own and cannot add a field to. The data should live exactly as long as the object. The program attaches 1 KB to each of 100,000 short-lived requests, once with a HashMap and once with a WeakHashMap, and measures the heap after garbage collection.

Java
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() are approximate):

Output
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 HashMap 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.
  • The WeakHashMap 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.
  • Its heap growth was well below the HashMap'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.
  • The map also keeps its grown bucket array. Like a HashMap, it enlarges the table while entries are added and never shrinks it when they go.
  • When the data belongs to a class rather than to individual objects, ClassValue (Java 7) is the better side table. It computes a value once per Class and lets class loaders be unloaded, which a WeakHashMap keyed by Class cannot promise if a value refers back to its class.

Traps: a map that changes by itself, and Cleaner

Because the garbage collector removes entries, a WeakHashMap can change between two lines of code that never touch it. The program shows the effect, and then Cleaner (Java 9), the tool for running cleanup code when an object dies.

Java
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));
    }
}
Output
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 remove. Stale entries are removed inside the map's own methods, by a private expungeStaleEntries step that size, get and put run first. Code that stores a size, or iterates while assuming entries stay put, can see different answers from one call to the next.
  • containsKey returned true, and then the entry disappeared once its key was dropped and a collection ran. A check followed by a separate get can therefore find nothing. Call get once, keep the result in a local variable, and test that for null.
  • The Cleaner action ran on the cleaner's own thread, Cleaner-0, 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.
  • The kept key still mapped to kept throughout, because the program held a strong reference to it.

WeakHashMap is not thread-safe, and the collector's removals count as changes, so wrap it with Collections.synchronizedMap when threads share it.

When to use WeakHashMap

Choosing a weak or caching structure
SituationUse
Attach data to objects you do not own, without keeping them aliveWeakHashMap<TheirObject, Data>
Cache with size limits or expiryA caching library such as Caffeine, or an LRU LinkedHashMap
Keys are strings, numbers or enumsA normal map; weak keys do not help
Listeners that should not keep their owners aliveA list of WeakReferences, or explicit unsubscribe
Free native resources when an object diesCleaner
Shared between threadsCollections.synchronizedMap(new WeakHashMap<>()); the class is not thread-safe
A value that refers to its keyWrap that reference in a WeakReference

An LRU cache with LinkedHashMap is shown on the TreeMap and LinkedHashMap page.