WeakReference vs SoftReference vs PhantomReference
Reference types control object reachability and cleanup behavior under GC.
📌 Key Idea
SoftReference 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 null2️⃣ 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 timing | When memory pressure increases | As soon as weakly reachable | After finalization phase, via queue |
get() behavior | Returns referent until cleared | Returns referent until cleared | Always null |
| Typical use case | Memory-sensitive cache | Canonical maps/listeners | Resource cleanup lifecycle hooks |
| Determinism | GC-policy dependent | GC timing dependent | Queue-driven notification only |
Interview Q&A
Quick Cheat Sheet
SoftMemory-sensitive cache candidate.
WeakDo not keep object alive.
PhantomCleanup notification after reclamation.