WeakHashMap
About
The WeakHashMap in Java is a specialized implementation of the Map interface that uses weak references for its keys. This allows keys that are no longer referenced elsewhere in the application to be garbage collected, making WeakHashMap a useful choice in caching and memory-sensitive applications.
Features
Weak Keys: The keys in a
WeakHashMapare stored as weak references. A weak reference does not prevent the key from being garbage collected. When a key is garbage collected, its corresponding entry is automatically removed from the map during the next operation on the map (like adding, removing, or querying).Null Values and Keys:
WeakHashMapallows onenullkey and multiplenullvalues.Not Thread-Safe:
WeakHashMapis not synchronized. If multiple threads access it concurrently, it must be synchronized externally.Efficient Cleanup: The map automatically cleans up entries whose keys are garbage collected, reducing memory overhead without explicit removal.
Use of ReferenceQueue:
WeakHashMapinternally uses aReferenceQueueto track weak references whose keys have been cleared by the garbage collector. This queue allows it to remove stale entries.
Internal Working of WeakHashMap
Key as WeakReference: Keys are wrapped in
java.lang.ref.WeakReferenceobjects, which allow the garbage collector to reclaim the memory used by the key if it is no longer strongly referenced.Automatic Removal: When the garbage collector reclaims a weak key, it adds the corresponding
WeakReferenceobject to theReferenceQueue.WeakHashMapprocesses this queue to remove stale entries.Structure: Internally,
WeakHashMapuses a hash table similar toHashMap. However, instead of using the key directly, it uses aWeakReferenceto wrap the key.Entry Removal: When performing operations like
put(),get(), orremove(),WeakHashMapchecks theReferenceQueuefor keys that have been cleared. It removes the entries associated with these keys from the map.
When to Use WeakHashMap
Caches: It is ideal for use in caches where the key should be automatically removed when it is no longer referenced elsewhere.
Listeners or Observers: When managing listeners or observers that should not prevent their associated objects from being garbage collected.
Memory-Sensitive Applications: In scenarios where memory optimization is critical, and you want to avoid memory leaks caused by unused keys.
Example Usage of WeakHashMap
import java.util.WeakHashMap;
public class WeakHashMapExample {
    public static void main(String[] args) {
        WeakHashMap<Object, String> weakMap = new WeakHashMap<>();
        Object key1 = new Object();
        Object key2 = new Object();
        weakMap.put(key1, "Value1");
        weakMap.put(key2, "Value2");
        System.out.println("Before GC: " + weakMap); // Before GC: {java.lang.Object@hashcode=Value1, java.lang.Object@hashcode=Value2}
        // Remove strong references
        key1 = null;
        // Request garbage collection
        System.gc();
        // Allow some time for GC to run
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("After GC: " + weakMap); // After GC: {java.lang.Object@hashcode=Value2}
    }
}Advantages of WeakHashMap
Prevents Memory Leaks: Automatically removes entries for keys that are no longer used, helping to manage memory efficiently.
Lightweight Caching: Simplifies cache implementation without the need for manual cleanup.
Integration with GC: Works seamlessly with the garbage collector to clean up unused entries.
Disadvantages of WeakHashMap
Unpredictable Entry Removal: Entry removal depends on the garbage collector. This can make behavior unpredictable.
Not Thread-Safe: Requires external synchronization in multithreaded applications.
Not Suitable for Strong References: If strong references to the keys exist, entries will not be removed.
Last updated