Java Core & JVM (50 Qs)•Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)
What are Strong, Soft, Weak, and Phantom References in Java and how do they interact with GC?
senior LevelCode ExampleSystem Design
In Simple Words: Java provides four levels of object reachability to give developers control over memory lifecycle:
- Strong Reference: Default reference (
Object obj = new Object()). As long as an object has a strong reference chain from a GC root, it is never collected. - Soft Reference (
SoftReference<T>): Collected only when the JVM runs critically low on memory before throwingOutOfMemoryError. Ideal for in-memory memory-sensitive caches. - Weak Reference (
WeakReference<T>): Collected eagerly on the very next GC cycle if no strong references exist. Ideal for canonical mappings (WeakHashMap). - Phantom Reference (
PhantomReference<T>): Used withReferenceQueueto track when an object has been finalized and its memory reclaimed by the OS. Replacedfinalize()for releasing native, off-heap OS resources.
java
// Weak reference allows object to be reclaimed on next GC run:
WeakReference<HeavyReport> weakReport = new WeakReference<>(new HeavyReport());
System.gc();
HeavyReport report = weakReport.get(); // Returns null if GC collected it!