Java.Collections.What is the difference between HashMap and WeakHashMap? What is WeakHashMap used for?

Let’s talk about HashMap vs WeakHashMap, and why the second one is super useful in certain cases.


🔍 Main Difference

FeatureHashMapWeakHashMap
Key reference typeStrong referencesWeak references
Garbage collectionKeys are never GC’d if referencedKeys can be GC’d if not strongly referenced elsewhere
When key is GC’dKey-value pair stays in mapKey-value pair is automatically removed
Use caseGeneral-purposeCaches, memory-sensitive mappings

🎯 What is a Weak Reference?

In Java:

  • A strong reference prevents an object from being garbage collected (this is what HashMap uses).
  • 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

  1. 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.
  2. Listeners/observers
    • If a listener object is no longer referenced, let it be GC’d and remove it from the map automatically.
  3. 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:

WeakHashMap automatically 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.

This entry was posted in Без рубрики. Bookmark the permalink.