WeakHashMap holds its keys through weak references. When a key is no longer referenced anywhere else in the program, the garbage collector can reclaim it, and the map then removes that entry automatically. It is useful for caches or metadata attached to objects whose lifetime you don't control.
Key Points: • In a normal HashMap, being a key keeps an object alive, which can cause memory leaks in long-running caches. • In a WeakHashMap, only the keys are weak. The values are strongly held, so a value must not refer back to its own key, or the entry never goes away. • Entries disappear only after a garbage collection, so the timing is unpredictable. • It works with identity-like keys. String literals and small Integer values are cached by the JVM and stay reachable, so they are poor keys. • It isn't thread-safe. For serious caching, libraries like Caffeine offer weak keys plus size and time limits.
Code Example:
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
public class WeakHashMapDemo {
static class Session {
final String id;
Session(String id) { this.id = id; }
public String toString() { return "Session(" + id + ")"; }
}
public static void main(String[] args) throws InterruptedException {
Map<Session, String> weak = new WeakHashMap<>();
Map<Session, String> strong = new HashMap<>();
Session s1 = new Session("A");
Session s2 = new Session("B");
weak.put(s1, "cart for A");
strong.put(s2, "cart for B");
s1 = null; // no other reference to session A
s2 = null; // the HashMap still holds session B
for (int i = 0; i < 10 && !weak.isEmpty(); i++) {
System.gc();
Thread.sleep(100);
}
System.out.println("WeakHashMap size after GC: " + weak.size());
System.out.println("HashMap size after GC: " + strong.size());
}
}Output:
WeakHashMap size after GC: 0 HashMap size after GC: 1
Good to Know: System.gc() is only a request, so on some JVMs the weak entry may survive a little longer. In real applications you never call it; entries are removed during normal garbage collection.
Interview Tip: A concise interview answer is:
"WeakHashMap holds its keys with weak references, so once a key isn't used anywhere else, the garbage collector can reclaim it and the entry is removed automatically. I'd use it for metadata or caches tied to objects whose lifetime I don't control, to avoid memory leaks, keeping in mind that values are held strongly and must not refer back to their keys."
Previous question: What is a BlockingQueue, and how do you use it for the producer–consumer problem?