Skip to lesson

WeakHashMap and safe caches

A cache trades memory for speed, and a cache with no limit is a memory leak with a nice name. Java offers two tools that look like automatic fixes, WeakHashMap and soft references, and one plain tool that actually bounds memory: an LRU map built on LinkedHashMap.

WeakHashMap removes entries when keys become unreachable

WeakHashMap is a Map that holds its keys weakly, so an entry is removed automatically once its key can no longer be reached from anywhere else.

A WeakHashMap is a map that holds its keys through weak references.

Before: the variable student points strongly to a Student, and a WeakHashMap entry points to it weakly, which does not keep it alive. After student = null: no strong arrow is left, so GC frees the Student and the entry vanishes.

Example 1 · WeakHashMap entries vanish with their keys

WeakHashMapDemo.javaJava
import java.util.Map;import java.util.WeakHashMap;
class Student {    final String roll;
    Student(String roll) {        this.roll = roll;    }
    @Override    public String toString() {        return roll;    }}
public class WeakHashMapDemo {    public static void main(String[] args) throws InterruptedException {        // Extra data about students, owned by someone else (the admissions module).        Map<Student, String> hostelRoom = new WeakHashMap<>();
        Student asha = new Student("S101");        Student ravi = new Student("S102");        Student meena = new Student("S103");        hostelRoom.put(asha, "A-12");        hostelRoom.put(ravi, "B-07");        hostelRoom.put(meena, "C-21");        System.out.println("Before: " + hostelRoom.size() + " entries");
        ravi = null;              // Ravi leaves the college: admissions drops him        meena = null;        System.gc();        Thread.sleep(100);        // let the JVM finish queueing the cleared keys
        System.out.println("After GC: " + hostelRoom.size() + " entry");        System.out.println("Left: " + hostelRoom + ", still used: " + asha.roll);    }}
Sample output
Before: 3 entries
After GC: 1 entry
Left: {S101=A-12}, still used: S101

What this code does

  • The map holds the three Student keys weakly. After ravi and meena are set to null, nothing else reaches those two objects, so the GC clears their keys and the map drops both entries, room numbers included.
  • asha is still a strong local variable used later, so her entry stays. The GC timing makes this a sample output, but on HotSpot with default settings it prints these lines.

When a key object is no longer strongly reachable anywhere else, the GC clears that weak reference, and the map removes the whole entry, value included, the next time you call almost any method on it (size, get, put and so on). It fits one job: attaching extra data to objects that someone else owns, so the data disappears together with the object. For example, the hostel module keeps a room number per Student object, while the admissions module decides how long each Student lives. Two details matter. Only keys are weak; values are held strongly. And keys are compared with equals and hashCode like a normal HashMap, so the map is meant for keys that are compared by identity, such as objects without their own equals.

Traps: literal String keys, values that point to their keys

A WeakHashMap entry disappears only when its key becomes unreachable, and some keys never do.

Example 2 · Two traps: keys that never die, values that hold keys

WeakHashMapTrapsDemo.javaJava
import java.lang.ref.WeakReference;import java.util.Map;import java.util.WeakHashMap;
class Order {    final String id;
    Order(String id) {        this.id = id;    }}
class Receipt {    final Order order;    final int amount;
    Receipt(Order order, int amount) {        this.order = order;        this.amount = amount;    }}
public class WeakHashMapTrapsDemo {    static void gcAndWait() throws InterruptedException {        System.gc();        Thread.sleep(100);    }
    public static void main(String[] args) throws InterruptedException {        // Trap 1: keys that are always reachable somewhere else.        Map<Object, String> map = new WeakHashMap<>();        map.put("CSE", "literal key");        map.put(100, "small Integer key");        map.put(new String("ECE"), "new String key");        gcAndWait();        System.out.println("Trap 1 keys left: " + map.keySet());
        // Trap 2: the value holds its own key strongly.        Map<Order, Receipt> receipts = new WeakHashMap<>();        Order o = new Order("ORD-1");        receipts.put(o, new Receipt(o, 250));        o = null;        gcAndWait();        System.out.println("Trap 2 entries left: " + receipts.size());
        // Fix: the value holds the key only weakly (or not at all).        Map<Order, WeakReference<Receipt>> fixed = new WeakHashMap<>();        Order o2 = new Order("ORD-2");        Receipt r2 = new Receipt(o2, 400);        fixed.put(o2, new WeakReference<>(r2));        o2 = null;        r2 = null;        gcAndWait();        System.out.println("Fixed entries left: " + fixed.size());    }}
Sample output
Trap 1 keys left: [100, CSE]
Trap 2 entries left: 1
Fixed entries left: 0

What this code does

  • Trap 1: only the new String("ECE") key is removed. "CSE" is a pooled literal and 100 comes from the Integer cache, so both stay strongly reachable from elsewhere and their entries never go.
  • Trap 2: the Receipt value holds its Order key, and the map holds the value strongly, so the entry survives every GC. Holding the value through a WeakReference (or storing just the order id) lets the entry go.

A string literal such as "CSE" is kept in the String pool and referenced by the class that uses it, so it normally lives as long as that class is loaded. Small Integer keys from autoboxing (-128 to 127) come from the Integer cache and live for the whole run. Entries with such keys are never removed. The second trap is a value that refers to its own key. The map holds the value strongly, the value holds the key strongly, so the key is always reachable and the entry stays for ever: a leak inside the very map that was meant to prevent one. Fixes: use keys that are real objects with a lifetime of their own; never let the value hold the key (store an id instead), or wrap the value in a WeakReference when it must point back.

Why soft-reference caches behave badly under load

A cache of SoftReference values sounds perfect: keep everything, let the GC drop entries when memory is short. In practice it fails exactly when you need it.

Example 3 · A soft-reference cache under a load spike

SoftCacheUnderLoad.javaJava
import java.lang.ref.SoftReference;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class SoftCacheUnderLoad {    static final Map<Integer, SoftReference<byte[]>> cache = new HashMap<>();    static int dbLoads = 0;
    static byte[] marksheet(int roll) {        SoftReference<byte[]> ref = cache.get(roll);        byte[] data = (ref == null) ? null : ref.get();        if (data == null) {            data = new byte[100_000];          // pretend: a slow database read, about 100 KB            dbLoads++;            cache.put(roll, new SoftReference<>(data));        }        return data;    }
    static int readAll() {        int before = dbLoads;        for (int roll = 1; roll <= 100; roll++) {            marksheet(roll);        }        return dbLoads - before;    }
    public static void main(String[] args) {        System.out.println("Warm-up, database loads: " + readAll());        System.out.println("Quiet time, database loads: " + readAll());
        // Result day: a burst of requests holds 20 MB of other data at once.        List<byte[]> busy = new ArrayList<>();        for (int i = 0; i < 20; i++) {            busy.add(new byte[1_000_000]);        }        System.out.println("Under load, database loads: " + readAll());        System.out.println("Map entries: " + cache.size() + ", busy blocks: " + busy.size());    }}
Sample output
Warm-up, database loads: 100
Quiet time, database loads: 0
Under load, database loads: 0
Map entries: 100, busy blocks: 20

What this code does

  • With a big default heap, the 100 cached marksheets (about 10 MB) survive the burst, and the third round needs no database loads. This is how a soft cache looks in testing: fine.
  • The Map itself never shrinks: 100 keys and 100 SoftReference objects stay even if their marksheets are cleared. Example 4 runs the same code with a smaller heap.

Example 4 · The same cache with a 32 MB heap: a stampede

Terminal
java -Xmx32m -Xlog:gc SoftCacheUnderLoad
Sample output
[0.016s][info][gc] Using G1
Warm-up, database loads: 100
Quiet time, database loads: 0
[0.214s][info][gc] GC(0) Pause Young (Concurrent Start) (G1 Humongous Allocation) (Evacuation Failure) 26M->26M(32M) 34.868ms
...
[0.221s][info][gc] GC(3) Pause Full (G1 Compaction Pause) 31M->19M(32M) 3.806ms
...
[0.231s][info][gc] GC(6) Pause Full (G1 Compaction Pause) 26M->26M(32M) 3.304ms
...
[0.236s][info][gc] GC(9) Pause Full (G1 Compaction Pause) 27M->27M(32M) 3.429ms
...
[0.240s][info][gc] GC(11) Pause Full (G1 Compaction Pause) 28M->28M(32M) 2.757ms
...
[0.246s][info][gc] GC(16) Pause Full (G1 Compaction Pause) 30M->30M(32M) 2.418ms
Under load, database loads: 100
Map entries: 100, busy blocks: 20

What this code does

  • A real run on HotSpot (JDK 21, G1), with Young and Concurrent lines cut. The burst fills the heap, a Full GC clears every soft marksheet (31M->19M), and the next round reloads all 100 from the database at once.
  • Then the reloaded entries fill the heap again and Full GCs run back to back while freeing almost nothing. On result day this is a slow server and a hammered database, at the worst possible moment.

Under a load spike, memory gets tight, the GC clears all soft entries at about the same time, and every request goes to the database at once: a cache stampede. Soft references also make the GC work harder: the heap looks full all the time, collections run more often and take longer, and heap graphs no longer show how much memory the program really needs. Finally, the map's keys and empty SoftReference objects stay behind unless you remove them, so the map itself can still grow without limit. For these reasons, most real services use a cache with an explicit size limit and a clear eviction rule instead of soft references.

A bounded LRU cache with LinkedHashMap and removeEldestEntry

An LRU cache (least recently used) has a fixed maximum size; when it is full, it throws out the entry that was used longest ago.

Example 5 · A bounded LRU cache in 15 lines

LruCacheDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;
class LruCache<K, V> extends LinkedHashMap<K, V> {    private final int maxEntries;
    LruCache(int maxEntries) {        super(16, 0.75f, true);           // true = access order: get() moves an entry to the end        this.maxEntries = maxEntries;    }
    @Override    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {        return size() > maxEntries;       // called after every put; true removes the eldest    }}
public class LruCacheDemo {    public static void main(String[] args) {        LruCache<String, String> trains = new LruCache<>(3);        trains.put("12627", "Karnataka Express");        trains.put("12951", "Mumbai Rajdhani");        trains.put("12301", "Howrah Rajdhani");        System.out.println("Full:        " + trains.keySet());
        trains.get("12627");                       // used again: becomes most recent        System.out.println("After get:   " + trains.keySet());
        trains.put("22691", "Bengaluru Rajdhani");        System.out.println("After put:   " + trains.keySet());        System.out.println("Size stays:  " + trains.size());    }}
Output
Full:        [12627, 12951, 12301]
After get:   [12951, 12301, 12627]
After put:   [12301, 12627, 22691]
Size stays:  3

What this code does

  • super(16, 0.75f, true) turns on access order, so get("12627") moves Karnataka Express to the end. removeEldestEntry returns true once the size goes over 3.
  • When Bengaluru Rajdhani is added, the front entry, Mumbai Rajdhani (used longest ago), is removed. However many trains are searched, the cache never holds more than 3.

LinkedHashMap gives you one in a few lines: the constructor new LinkedHashMap<>(16, 0.75f, true) keeps entries in access order (every get or put moves an entry to the end), and removeEldestEntry is called after each put; when it returns true, the oldest entry at the front is removed. The memory use is now bounded by design: at most N entries, whatever the traffic. You choose N from measurements, and the hit rate tells you whether N is big enough. LinkedHashMap is not thread-safe, and in access-order mode even get changes the map. Wrap it with Collections.synchronizedMap for simple shared use; busy servers usually use a cache library such as Caffeine, which also offers time-based expiry.

Pass true as the third constructor argument. With the default insertion order, get does not refresh an entry, and the cache becomes FIFO (first in, first out) instead of LRU.

Next step

Check your understanding

12 quick questions