Let’s talk about HashMap vs WeakHashMap, and why the second one is super useful in certain cases.
🔍 Main Difference
| Feature | HashMap | WeakHashMap |
|---|---|---|
| Key reference type | Strong references | Weak references |
| Garbage collection | Keys are never GC’d if referenced | Keys can be GC’d if not strongly referenced elsewhere |
| When key is GC’d | Key-value pair stays in map | Key-value pair is automatically removed |
| Use case | General-purpose | Caches, memory-sensitive mappings |
🎯 What is a Weak Reference?
In Java:
- A strong reference prevents an object from being garbage collected (this is what
HashMapuses). - A weak reference does not prevent GC. If no strong references exist, the object is eligible for GC — even if it’s a key in a
WeakHashMap.
import java.util.*;
public class WeakHashMapExample {
public static void main(String[] args) {
Map<Object, String> map = new WeakHashMap<>();
Object key = new String("weakKey");
map.put(key, "value");
System.out.println("Before GC: " + map);
key = null; // Remove strong reference
System.gc(); // Suggest garbage collection
// Wait a bit for GC to kick in
try { Thread.sleep(1000); } catch (InterruptedException e) {}
System.out.println("After GC: " + map);
}
}
🔍 Output:
Before GC: {weakKey=value}
After GC: {}
The entry was automatically removed because the key was garbage collected.
✅ Use Cases for WeakHashMap
- Caches or memory-sensitive storage
- You don’t want to prevent objects from being GC’d.
- If the key is no longer used elsewhere, remove the mapping.
- Listeners/observers
- If a listener object is no longer referenced, let it be GC’d and remove it from the map automatically.
- Class metadata or custom class loaders
- Used internally by Java for class metadata that should not prevent class unloading.
⚠️ Warnings
- You shouldn’t rely on when GC happens — it’s non-deterministic.
- Not thread-safe. Wrap with
Collections.synchronizedMap()if needed.
🧠 TL;DR:
✅
WeakHashMapautomatically removes entries when keys are no longer in use elsewhere (i.e., garbage collected).
🧠 Use it when you want to associate data with objects but don’t want those associations to prevent GC — like in caches or observers.