Q39: What are Strong, Soft, Weak, and Phantom References in Java?
- Strong Reference: Standard reference (
Object obj = new Object()). Never garbage collected while reachable. - Soft Reference (
SoftReference): Collected ONLY when heap runs low on memory. Excellent for in-memory caches. - Weak Reference (
WeakReference): Collected immediately on the next GC pass if no strong references exist. Used inWeakHashMap. - Phantom Reference (
PhantomReference): Enqueued toReferenceQueueafter object is finalized. Used for resource cleanup.
Key Takeaways
- Soft = Reclaimed when memory runs out (Caching).
Weak = Reclaimed on next GC pass (
WeakHashMap). Phantom = Pre-mortem cleanup tracking.
Knowledge Check
Which reference type is ideal for building memory-sensitive caches that release items when JVM runs low on memory?