🧩 What is a WeakHashMap
?
A WeakHashMap
is a hash table-based map where the keys are stored as weak references.
If a key is no longer referenced elsewhere in your application, then the entry will be automatically removed by the garbage collector — poof 💨
It’s like a self-cleaning map that helps you avoid memory leaks when you’re associating data with objects you don’t “own”.
🔍 How It Works
- Uses
WeakReference
for its keys. - When a key becomes weakly reachable (no strong refs), the GC collects it, and the map removes the entry automatically.
- Internally, it uses a
ReferenceQueue
to track which keys were GC’d and should be cleaned up.
🧪 Code Example
import java.util.*;
public class WeakHashMapDemo {
public static void main(String[] args) {
Map<Object, String> map = new WeakHashMap<>();
Object key = new String("weak-key"); // not interned!
map.put(key, "value");
System.out.println("Before GC: " + map);
key = null; // remove strong reference
System.gc(); // suggest garbage collection
try { Thread.sleep(500); } catch (InterruptedException ignored) {}
System.out.println("After GC: " + map); // likely empty now
}
}
Before GC: {weak-key=value}
After GC: {}
✅ Use Cases
- Memory-sensitive caches
- You want to store metadata, but only while the object is still in memory.
- Class loader metadata
- Common in frameworks that associate data with classes, but don’t want to prevent class unloading.
- Listeners or observers
- If the observer object disappears, you want it removed automatically from the registry.
🚫 When Not to Use It
- When you need deterministic lifetime of entries — GC is non-deterministic!
- For performance-critical or large-scale apps,
WeakHashMap
can be slower and less predictable than alternatives likeConcurrentHashMap
.
🧠 Key Differences from HashMap
Feature | HashMap | WeakHashMap |
---|---|---|
Key reference type | Strong | Weak (WeakReference ) |
Automatic cleanup | ❌ No | ✅ Yes, on GC of keys |
Allows null key | ✅ Yes | ✅ Yes |
Thread-safe | ❌ No | ❌ No |
GC-aware | ❌ | ✅ Removes entries post-GC |
💡 TL;DR:
WeakHashMap
is a special kind of Map where keys are held with weak references — so when a key is no longer used anywhere else, its entry is automatically removed after garbage collection.
Perfect for caches, framework internals, and memory-sensitive metadata.