← Home
🏗Crack System Design with DSA AnimatorSystem DesignNEW
🏗 System Design›Concurrency & Threading

🫧WeakHashMap

Map entries disappear automatically when keys are no longer strongly reachable.

📌 Key IdeaWeakHashMap is useful for caches/metadata keyed by object identity/lifecycle. Keys are weakly referenced, so GC can reclaim them and remove entries. Do not use it for deterministic storage or critical business data.
🧩

Problem it solves

  • Metadata/caches keyed by objects can accidentally retain those objects forever (memory leak).
  • Manual cleanup is easy to forget and hard to keep correct at scale.
  • WeakHashMap ties entry lifetime to key reachability so GC can reclaim entries automatically.
🖼

Visual

🫧 Weak keys and GC-driven cleanup
WeakHashMap stores keys via WeakReference

Strong ref exists:
  key --------> object
  map entry stays

No strong ref:
  key eligible for GC
  GC clears weak ref
  entry removed on next map operation/cleanup

Lifetime of entry is tied to key reachability, not explicit remove calls.

✅

When to Use

  • Attaching metadata to objects without extending their lifetime.
  • Memory-sensitive auxiliary caches keyed by object instances.
  • Framework internals where entries should vanish when owners vanish.
🚫

When NOT to Use

  • Business-critical maps requiring deterministic retention.
  • Caches where keys are primitives/strings held strongly elsewhere forever.
  • Concurrent high-write maps (WeakHashMap is not thread-safe).
💻

Code Variations

1️⃣ Basic usagejava
Map<Object, String> m = new WeakHashMap<>();
Object key = new Object();
m.put(key, "metadata");

key = null;     // drop strong reference
System.gc();    // eventual cleanup (not guaranteed immediately)
Entry can disappear after GC cycle and subsequent map activity.
2️⃣ Common pitfall (accidental strong refs)java
WeakHashMap<Key, Value> cache = new WeakHashMap<>();
List<Key> allKeys = new ArrayList<>(); // keeps keys strongly reachable

cache.put(k, v);
allKeys.add(k); // entry will not be reclaimed
Any other strong reference to key defeats weak-key eviction.
📊

HashMap vs WeakHashMap

AspectHashMapWeakHashMap
Key reference typeStrong referenceWeak reference
Entry lifetimeUntil explicit remove/clearUntil key loses strong reachability + GC
DeterminismDeterministic retentionNon-deterministic (GC timing)
Thread safetyNot thread-safeNot thread-safe
🔀

Common Confusions Cleared Up

WeakHashMap is GC-assisted cleanup, not a full cache policy

It does not provide size-based eviction (LRU/LFU), TTL, or predictable removal timing. Pair with dedicated caches (Caffeine/Guava) when you need policy-driven eviction.

🎤

Interview Q&A

🧾

Quick Cheat Sheet

Core ideaWeak keys let GC reclaim entries.
Not guaranteedImmediate removal timing.
Not includedTTL/LRU/size-based eviction policies.
RuleAvoid unintended strong references to keys.
🔗

Related Topics