Lesson · Garbage Collection & References
Reference types: soft, weak, phantom and Cleaner
16 min readReference Types
An ordinary reference is a command to keep an object alive. The java.lang.ref package turns that command into a negotiation: four strengths, one queue, and a cleanup pipeline that runs after the object is gone.
Four strengths, four questions
A normal reference is a command: keep this alive, no matter what. The java.lang.ref package turns that command into a negotiation, and the three reference classes are the answers to one question. If memory gets tight, what may the collector do to this object?
Reachability has an order, checked from the strongest handle down: strongly, softly, weakly, phantom reachable. An object is collected only when no strong, soft or weak handle remains. A phantom handle does not keep the object usable at all; it reports on the way out.
| Strength | What the collector may do | Typical use |
|---|---|---|
| Strong (normal) | nothing: collected only when no root path reaches it | everything ordinary |
| Soft | clear the reference and free the object when memory pressure demands it | memory-sensitive caches of recomputable data |
| Weak | clear it once only weak references remain; the next collection is enough | canonical maps, listener registries, WeakHashMap keys |
| Phantom | never expose the referent through get(); enqueue the reference after the end | cleanup pipelines, the mechanism behind Cleaner |
The choice is a question, not a feature. Ask what losing this object would be allowed to mean, and the answer names the strength. This lesson is the mechanism behind the overview in the object lifecycle lesson.
Soft: keep it until memory says otherwise
A SoftReference holds its referent while memory is comfortable and lets go when it is not. The collector clears soft references before it gives up and throws OutOfMemoryError, which is exactly the shape a cache wants: keep what fits, drop what does not.
The catch is in the specification. Soft references are cleared at the implementation's discretion, so the timing, the policy and the definition of pressure belong to the collector you are running. HotSpot clears a soft reference roughly when it has been idle for -XX:SoftRefLRUPolicyMSPerMB milliseconds per free megabyte of heap (1000 by default): useful behaviour to observe, not a contract to build on.
The practical consequences are short. A soft cache is the right home for data you can recompute and the wrong home for data you must keep. On a large heap a soft reference can hold a surprising amount, because comfortable means something different at 32 GB than at 256 MB. And if you need eviction you can predict, an LRU with a size limit is what you actually want.
// A cache that returns memory before the heap fails: recomputable data only. Map<String, SoftReference<BufferedImage>> previews = new ConcurrentHashMap<>(); BufferedImage preview(String path) { SoftReference<BufferedImage> ref = previews.get(path); BufferedImage cached = ref == null ? null : ref.get(); if (cached == null) { // cleared, or never cached: both are a miss cached = render(path); // recompute is the normal path, not an error path previews.put(path, new SoftReference<>(cached)); } return cached; }
Soft is for keep if cheap, not for keep if important. If losing the value would be a bug, that is a strong reference or a real cache with a policy you control.
Weak: identity only
A WeakReference is cleared once the object is only weakly reachable, which in practice means the next collection after the last strong and soft handle goes away. get() returns the referent or null, and no promise is made about which collection it is: it is cleared precisely because nothing else needed it.
WeakHashMap is the standard pattern: keys are weak, values are strong, and an entry disappears once its key is no longer referenced anywhere else. It is the right structure for a canonicalizing map (an interner, metadata attached to objects you do not own) and the wrong one for a cache you expect to keep entries. The map polls the reference queue behind the scenes and expunges stale entries the next time you use it.
Two conditions have to hold for any of that to work. The key must implement equals and hashCode properly, since that contract decides whether an entry is even findable (the HashMap internals lesson covers it in full). And nothing else may hold the key strongly: a second map, a listener list, or a string literal key keeps entries alive forever.
// Keys are weak: an entry goes away once nothing else references the key. Map<Order, String> metadata = new WeakHashMap<>(); Order order = new Order(); metadata.put(order, "imported"); order = null; // the only strong reference to the key System.gc(); // a request, answered differently across collectors metadata.size(); // typically 0: the entry was expunged on this call
A weak reference does not keep anything alive; one strong reference anywhere wins. Weak says this handle identifies the object, it does not own it.
Phantom and the ReferenceQueue
A PhantomReference is the one handle you can never use. get() always returns null, by design: by the time the referent is phantom reachable it is on the way out, and offering a usable handle would resurrect exactly the object the collector is about to reclaim. What you get instead is a notification.
That notification is the ReferenceQueue mechanics. A reference can be constructed with a queue, and the collector enqueues it once the referent has been cleared. poll() returns a queued reference or null immediately; remove() blocks until one arrives (or a timeout expires); isEnqueued() tells you whether this reference is sitting in its queue; clear() drops the reference's own link, which cancels the notification. A phantom reference is enqueued after the referent is finally unreachable (and after finalization, if the object ever needed it), which makes the arrival a post-mortem event: it tells you the object is gone, and it never lets you touch it.
- Register at construction: new PhantomReference<>(obj, queue) is the only way to receive the notification. A reference built without a queue is a handle that can neither be used nor heard from.
- poll vs remove: poll suits a worker loop that has other things to do; remove blocks a dedicated cleanup thread until the next reference arrives.
- isEnqueued: how a reference reports that it has been handed over without consuming it from the queue.
- clear: drops the reference's link to the referent; a cleared reference is never enqueued, which is also how a notification is cancelled.
Phantom is a post-mortem notification, not a handle. It tells you the object is gone; it never gives you a way back to it.
Reference strengths · one object, four handles
never collected while reachable
cleared only under pressure
cleared once only weakly reachable
get() is always null
One Payload object, four ways to reference it. The strong handle keeps it alive the way every normal field does; the other three are java.lang.ref handles, and each answers a different question about what may happen when memory gets tight.
The story pins each transition to a cycle; real collectors decide the soft policy and the exact cycle themselves, which is why nothing correctness-critical should depend on them.
Cleaner: the supported safety net
java.lang.ref.Cleaner arrived in Java 9 as the supported way to run cleanup when an object becomes unreachable. Cleaner.register(object, runnable) returns a Cleanable: the runnable is the cleaning action, it must not reference the object it cleans (or it would keep that object alive forever), and Cleanable.clean() runs the action once. A second call does nothing.
The details that matter: the action runs on a cleaner thread at no predictable time and only if the object actually became unreachable without clean() having been called first. That makes a Cleaner the right tool for a safety net and the wrong tool for a contract. Freeing direct ByteBuffer memory, or catching a handle someone forgot to close, are the intended cases; the native side of that story belongs to the Runtime Memory Areas topic.
Which leaves the rule where it always was: close() deterministically with try-with-resources, and register the Cleaner so a missed close does not hold a file descriptor or a native allocation until the process dies. The explicit path is the design; the Cleaner is the insurance.
public final class NativeBuffer implements AutoCloseable { private static final Cleaner CLEANER = Cleaner.create(); // The action holds the state, never the buffer: it must not resurrect the owner. private static final class State implements Runnable { private long address; State(long address) { this.address = address; } @Override public void run() { if (address != 0) { free(address); // the native release address = 0; // a second run does nothing } } } private final State state; private final Cleaner.Cleanable cleanable; NativeBuffer(long bytes) { this.state = new State(allocate(bytes)); // native memory lives in state this.cleanable = CLEANER.register(this, state); // and is freed by the regular object } @Override public void close() { cleanable.clean(); // runs the action now, on this thread, exactly once } }
Cleaner is a safety net, not a destructor: close() is still your job. If the cleanup must happen before a deadline, only close() can promise that.
Reference types · one object, four handles
the strong handle is dropped before GC 1
Strong
kept until the handle goes away
Soft
cleared under pressure, at the implementation's discretion
Weak
cleared once only weakly reachable
Phantom
get() is always null; enqueued after the referent is gone
Cleaner lifecycle
Cleaner.register(obj, state) returns a CleanableThe cleaning action holds the state, never the object it cleans. Both paths release the same native resource; only one of them happens at a time your code chose, which is why close() stays the contract and the Cleaner stays the insurance.
Why finalize() is on its way out
finalize() was Java's first answer to post-mortem cleanup, and it is deprecated for removal. The problems are structural rather than stylistic: it runs when the collector decides, at most once, on a thread nobody chose, and a finalizable object takes an extra collection cycle to reclaim because the JVM keeps it alive until the finalizer has run.
- Unpredictable: no guarantee of when it runs, or whether it runs at all before the JVM exits, so correctness cannot depend on it.
- Resurrection: finalize() can store this somewhere reachable, and the object comes back to life, which the collector then has to tolerate.
- Cost: finalizable objects are discovered, queued and finalized on a separate thread; a backed-up queue keeps those objects alive longer, and each one needs two cycles to disappear.
- Silent failure: an exception thrown inside finalize() is ignored, so broken cleanup fails with no signal at all.
Do not add finalize() to new code, and do not rely on it in old code. The supported replacement is Cleaner, and the deterministic answer was always close().
Building a cleanup pipeline
Cleaner and a hand-rolled ReferenceQueue share one shape: keep the state needed to clean up in a separate object, hand that state to the reference mechanism, and let a worker act on the notifications. The separate state object solves resurrection for free: because the cleaning action never references the object being cleaned, the reference can be cleared and the object collected as soon as your code stops using it.
- Put the resource state in a small static class: the file handle, the native pointer, the facts the release needs, plus an idempotent release method.
- Give the owner class an explicit close() that calls cleanable.clean(); the explicit path runs the release now, and a second call is a no-op.
- Register in the constructor: CLEANER.register(this, state). The cleaning action holds the state, never the owner.
- For queue-based pipelines, construct each reference with the queue and have one thread loop on remove() (or poll() if it has other work to do).
- Treat every notification as a bug report: the safety net fired because somebody forgot close(), which is worth logging, not a mechanism to lean on.
The pipeline is a safety net with a log line, not the primary path. The primary path is close() on every code path, including the exceptional ones.
What to remember
The four strengths, the queue discipline and the Cleaner rule, in one page:
- Strong always wins: while a strong path exists, no reference type can reclaim the object, and none can save it once the path is gone.
- Soft is pressure-sensitive and policy-free: cleared before OutOfMemoryError, at the implementation's discretion; keep recomputable data there, not valuable data.
- Weak is identity only: WeakHashMap for keys you do not own; the entry goes when the key does, as long as nothing else holds the key strongly.
- Phantom plus a queue is how a pipeline hears about collection: the notification is post-mortem and the referent is never touchable.
- Cleaner over finalize: registered once, run at most once, no resurrection, and still not on a schedule. close() comes first, always.
Soft for keep if cheap, weak for identity only, phantom for tell me when it is gone. The handle you choose is a statement about what losing the object is allowed to mean.
A weak key is not a weak entry
WeakHashMap weakens the key and only the key. The value is held strongly, so if the value references its own key (an entry that maps an object to its own metadata, say), the key stays reachable through the map itself and the entry never leaves. The same happens when the key is reachable from anywhere else: a static cache, an interned string, a boxed Integer held by the JDK. Before trusting a weak map, prove that nothing else holds the key strongly, and check that the value does not contain the key.
Interview angles
What happens to a soft reference under memory pressure?+
The collector may clear it, and clearing happens before OutOfMemoryError is thrown. Whether and when it clears is left to the implementation, so the cache has to treat every get() as possibly null.
HotSpot watches how long a soft reference has been idle relative to free heap (-XX:SoftRefLRUPolicyMSPerMB, 1000 by default), which is why a soft cache holds more on a big heap. Build the cache so a miss is a recomputation, and it stays correct whatever the collector does.
Common misconception: That a soft reference is an LRU entry. Nothing in the API promises recency-based eviction, or eviction at all until pressure is real.
Follow-up: When would you deliberately not use soft references for a cache?
When is a weak reference cleared?+
Once the object is only weakly reachable, which is the next collection after the last strong or soft handle disappears.
The classic consumer is WeakHashMap: weak keys, strong values, an entry expunged when the key is no longer referenced anywhere else. The map processes a reference queue internally on its own operations rather than running a sweeper thread, which is why the entry disappears on the next call rather than at the exact moment of collection.
Follow-up: What would keep a WeakHashMap entry alive forever?
What is a phantom reference for?+
Notifications after the fact. get() always returns null, and the reference is enqueued once the referent is unreachable, which is how a cleanup pipeline learns that memory is about to be reclaimed.
The queue is the deliverable: the reference itself is a safe way to keep bookkeeping about an object while never holding the object. That is the mechanism Cleaner is built on.
Common misconception: That a phantom reference is a stronger kind of weak reference. It is weaker: it gives no access to the referent at all.
Why is finalize() deprecated for removal?+
Because it is unpredictable (at most once, unknown thread, possibly never), it can resurrect objects, it costs an extra collection cycle per finalizable object, and failures inside it are silently ignored.
None of those are tuning problems; they are the semantics of a language feature that promised deterministic cleanup from a non-deterministic mechanism. Cleaner replaced it for the cases where a safety net is genuinely needed.
Follow-up: What is the difference between finalize() and Cleaner in practice?
When would a Cleaner be the wrong tool?+
Whenever correctness needs the release to happen at a known moment: files, sockets, locks and any pooled resource. Cleaner timing has no promise at all, so close() has to be the contract.
A Cleaner is also wrong for cheap cleanup that is already handled, since every registration costs a phantom reference and a slot on the cleaner thread. Use it for native or otherwise unmanaged state, and treat a firing Cleaner as evidence of a missed close().