What are strong, soft, weak and phantom references in Java?
A strong reference prevents collection. A soft reference is cleared only when memory is short, a weak reference is cleared at the next collection once no strong refs remain, and a phantom reference is used to know when an object has been reclaimed.
Explain it simply
Strong is holding a book in your hand: nobody takes it. Soft is a book left on the table, which the librarian removes only when shelf space is running out. Weak is a sticky note on the wall, thrown away at the next cleaning. Phantom is a notification that the book has already been taken away.
Example
import java.lang.ref.*;
import java.util.*;
Object strong = new Object(); // normal reference
SoftReference<byte[]> soft = new SoftReference<>(new byte[1000]); // cache-like data
WeakReference<Object> weak = new WeakReference<>(new Object());
// after a GC the weak target is typically gone:
// weak.get() may return null (not guaranteed to be immediate)
Map<Object, String> metadata = new WeakHashMap<>(); // entry disappears when the key is unreachable elsewhereWhat to say in the interview
"Strong references are the default and keep objects alive. SoftReference suits memory-sensitive caches, since the JVM clears them before throwing OutOfMemoryError. WeakReference does not keep its target alive and underlies WeakHashMap, which is useful for attaching metadata to objects without leaking them. PhantomReference's get always returns null and is used with a ReferenceQueue for cleanup after collection, and has largely taken over from finalize. I always check get() for null before using it."
Common mistakes
- Using soft references for a production cache without sizing limits.
- Keeping a strong reference elsewhere and wondering why the weak one never clears.