HashMap and WeakHashMap are implementations of the Map interface, but they differ significantly in how they interact with the Garbage Collector (GC). The key difference lies in the type of reference used for map keys.
HashMap
HashMap stores key–value pairs using strong references for keys. As long as a key is present in a HashMap, it is not eligible for garbage collection, even if no other references to that key exist.
The entries remain in the map until explicitly removed.
Example: HashMap and Garbage Collection
This depicts that HashMap maintains a strong reference to its keys. Even after removing the external reference and invoking garbage collection, the key–value pair remains in the map.
import java.util.*;
class HashMapDemo {
public static void main(String[] args) throws Exception {
HashMap<Demo, String> map = new HashMap<>();
Demo d = new Demo();
map.put(d, "Hi");
System.out.println(map);
d = null;
System.gc();
Thread.sleep(4000);
System.out.println(map);
}
}
class Demo {
public String toString() {
return "demo";
}
protected void finalize() {
System.out.println("Finalize method is called");
}
}
Output:
{demo=Hi}
{demo=Hi}
Explanation: Even after removing the external reference (d = null), the object remains reachable through the HashMap, preventing garbage collection.
WeakHashMap
WeakHashMap stores keys using weak references. If a key has no strong references elsewhere, it becomes eligible for garbage collection, and the corresponding entry is automatically removed.
Garbage Collector dominates over WeakHashMap.
Example: WeakHashMap and Garbage Collection
This code example shows how WeakHashMap uses weak references for its keys. Once the key loses its strong reference, the garbage collector removes the entry automatically from the map.
import java.util.*;
class WeakHashMapDemo {
public static void main(String[] args) throws Exception {
WeakHashMap<Demo, String> map = new WeakHashMap<>();
Demo d = new Demo();
map.put(d, "Hi");
System.out.println(map);
d = null;
System.gc();
Thread.sleep(4000);
System.out.println(map);
}
}
class Demo {
public String toString() {
return "demo";
}
protected void finalize() {
System.out.println("Finalize method is called");
}
}
Output:
{demo = Hi}
finalize method is called
{ }
Explanation: Once the key loses its strong reference, it is garbage collected and the corresponding map entry is removed automatically.
Strong vs Weak References
Reference Type | Description |
|---|---|
Strong Reference | Default reference type; object is not eligible for GC |
Weak Reference | Object becomes eligible for GC when no strong references exist |
HashMap vs WeakHashMap – Key Differences
Feature | HashMap | WeakHashMap |
|---|---|---|
Reference Type | Strong | Weak |
GC Behavior | Prevents GC | Allows GC |
Entry Removal | Manual | Automatic |
Memory Leaks | Possible | Less likely |
Implements Cloneable | Yes | No |
Typical Use Case | General-purpose storage | Caches, metadata storage |