Java / Java 17 Garbage Collection Interview Questions
What is the difference between soft, weak, and phantom references?
Beyond ordinary strong references, Java's java.lang.ref package offers three progressively weaker reference types that change how eagerly the GC reclaims the referent.
| Type | Cleared | Typical use |
| SoftReference | Only right before an OutOfMemoryError | Memory-sensitive caches |
| WeakReference | At the next GC cycle once unreachable | WeakHashMap keys, canonicalizing maps |
| PhantomReference | Never returns the referent; queued after finalization | Post-mortem cleanup via ReferenceQueue / Cleaner |
SoftReference<byte[]> cache = new SoftReference<>(loadLargeData()); WeakReference<Session> sessionRef = new WeakReference<>(session); ReferenceQueue<Resource> queue = new ReferenceQueue<>(); PhantomReference<Resource> cleanupRef = new PhantomReference<>(resource, queue);
Phantom references are notable because get() always returns null for them - they exist purely so code can be notified, via a ReferenceQueue, exactly when an object has become phantom-reachable, which is the mechanism the modern java.lang.ref.Cleaner API uses in place of the deprecated finalize().
More Related questions...