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

🧷WeakReference vs SoftReference vs PhantomReference

Reference types control object reachability and cleanup behavior under GC.

📌 Key IdeaSoftReference is for memory-sensitive caching, WeakReference for canonical maps/listeners where objects should vanish quickly, and PhantomReference for post-mortem cleanup with ReferenceQueue.
🖼

Visual

🧷 Java reference strength ladder
Strong  -> normal objects, never GC'd while reachable
Soft    -> collected under memory pressure (cache-friendly)
Weak    -> collected eagerly once no strong refs remain
Phantom -> already finalized; post-mortem cleanup tracking only
✅

When to Use

  • Soft references for best-effort in-memory cache values.
  • Weak references for maps/listeners that should not prolong key/object lifetime.
  • Phantom references for resource cleanup tracking after object reclamation.
🚫

When NOT to Use

  • Critical business state where retention must be deterministic.
  • Using phantom references as normal object access mechanism (always returns null).
💻

Code Variations

1️⃣ Weak referencejava
Object obj = new Object();
WeakReference<Object> ref = new WeakReference<>(obj);
obj = null; // remove strong ref
// after GC, ref.get() may become null
2️⃣ Soft reference cache sketchjava
SoftReference<byte[]> imageRef = new SoftReference<>(loadImage());
byte[] img = imageRef.get();
if (img == null) {
  img = loadImage(); // recreate after GC eviction
  imageRef = new SoftReference<>(img);
}
3️⃣ Phantom reference with queuejava
ReferenceQueue<ResourceHolder> q = new ReferenceQueue<>();
PhantomReference<ResourceHolder> p = new PhantomReference<>(holder, q);

// background thread:
Reference<? extends ResourceHolder> r = q.remove(); // blocks
cleanupNativeHandle();
Phantom refs are for cleanup notifications; referent is not directly accessible.
📊

Weak vs Soft vs Phantom

Aspect`SoftReference``WeakReference``PhantomReference`
Collection timingWhen memory pressure increasesAs soon as weakly reachableAfter finalization phase, via queue
get() behaviorReturns referent until clearedReturns referent until clearedAlways null
Typical use caseMemory-sensitive cacheCanonical maps/listenersResource cleanup lifecycle hooks
DeterminismGC-policy dependentGC timing dependentQueue-driven notification only
🎤

Interview Q&A

🧾

Quick Cheat Sheet

SoftMemory-sensitive cache candidate.
WeakDo not keep object alive.
PhantomCleanup notification after reclamation.
🔗

Related Topics