The Plain Picture#
A rope tying you to an object: as long as you hold it, the object stays. (Strong)
A rubber band: it holds, but if the room is running out of space, the cleaners may cut it. (Soft)
A thread: the cleaners cut it at the very next clean-up if nothing stronger is attached. (Weak)
A note saying "tell me when it's gone": you can't use the object through it at all. (Phantom)
The Real Names#
| Type | Collected when | Use |
|---|---|---|
| strong (a normal reference) | never, while reachable | everything by default |
SoftReference | only when memory is running low | memory-sensitive caches |
WeakReference | at the next GC, if only weakly reachable | caches keyed by objects (WeakHashMap — Collections, From the Inside Ch 10), listener registries |
PhantomReference | after it's been collected — used with a queue for clean-up notification | releasing native resources (java.lang.ref.Cleaner builds on it) |
Measured:
Object big = new byte[10_000_000];
WeakReference<Object> weak = new WeakReference<>(big);
System.out.println("before: " + (weak.get() != null)); // before: true
big = null; // remove the only strong reference
System.gc(); // a HINT to run a GC (not guaranteed)
System.out.println("after GC: " + (weak.get() != null)); // after GC: falsefinalize() — the old way to run clean-up when an object is collected — is deprecated: it's slow, unpredictable, and can resurrect objects. Use
try-with-resources for resources (Exceptions and Generics Ch 4), and Cleaner as a last-resort safety net.
Check yourself
3 questionsWhat happens to an object reachable only through a WeakReference?
Show answerHide answer
It's collected at the next GC, and get() then returns null.
Why is SoftReference suited to caches?
Show answerHide answer
Its referent survives until memory runs low, so cached data is kept while there's room and dropped under pressure.
What replaced finalize()?
Show answerHide answer
try-with-resources for deterministic clean-up, with java.lang.ref.Cleaner as a safety net.