CKTIS / Java
The lifecycle of weak, soft, and phantom references in Java
Learn when a reference can return its referent, what enters a reference queue, and how `reachabilityFence` keeps an object strongly reachable.
Version: Java SE 21
Syntax
Java SE 21 · java.lang.ref (module java.base)
new WeakReference<T>(referent)
new WeakReference<T>(referent, queue)
new SoftReference<T>(referent)
new SoftReference<T>(referent, queue)
new PhantomReference<T>(referent, queue)
new ReferenceQueue<T>()
// Registered constructors accept ReferenceQueue<? super T>.
T value = reference.get();
reference.clear();
boolean added = reference.enqueue();
Reference.reachabilityFence(referent);
// For a queue of type ReferenceQueue<T>:
Reference<? extends T> ready = queue.poll();
Reference<? extends T> next = queue.remove(); // throws InterruptedException
Reference<? extends T> timed = queue.remove(timeoutMillis); // long; throws InterruptedExceptionIn java.lang.ref (module java.base), the reference object and its referent are separate objects. When the garbage collector (GC) detects a weakly reachable object—one that is neither strongly nor softly reachable but can be reached by traversing a weak reference—it clears its WeakReference objects. The GC may clear SoftReference objects to softly reachable objects at its discretion in response to memory demand. The VM guarantees that it clears all such soft references before throwing OutOfMemoryError, but otherwise does not specify clearing time or order. PhantomReference supports cleanup notifications: the GC clears it upon detecting phantom reachability, and its get() always returns null.
Weak and soft constructors take either the referent alone or the referent and a ReferenceQueue<? super T>. The phantom constructor always takes a queue argument. Passing null as the queue means no registration. For Reference.get/clear/reachabilityFence, distinguish reading, clearing, and keeping an object alive. On a weak or soft reference, get() returns the referent or null if absent, for example after clearing. Read once, check for null, and use the same local result. clear() drops the link; by itself it neither enqueues the reference nor frees the referent. enqueue() clears the reference and attempts to add it to its registered queue explicitly, returning true on successful insertion.
The static Reference.reachabilityFence(obj) keeps obj strongly reachable through the call, even if the code has already stopped using it explicitly. Put the call in finally after the operation that needs the object to stay alive so it runs on exceptional paths too. Pass the object itself, not its weak, soft, or phantom reference wrapper. The fence does not trigger GC or finalization; passing null has no effect.
For ReferenceQueue.poll/remove, the item removed from a ReferenceQueue<T> is a Reference<? extends T>, not its referent. poll() removes and returns an available reference, or immediately returns null. remove() waits indefinitely for an entry. With a positive millisecond timeout, remove(long timeout) returns null on expiry and offers no real-time guarantee. A timeout of 0 waits indefinitely; a negative value throws IllegalArgumentException. Both remove overloads throw InterruptedException if the wait is interrupted.
The GC enqueues registered references when it clears them or later; that timing is not deterministic. An empty poll() does not mean the referent is still alive. Keep a strong reference to each registered wrapper while you need its notification: registration alone does not keep it alive. Do not rely on GC notifications to close resources on time.
Examples
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
public class ReferenceLifecycle {
public static void main(String[] args) throws InterruptedException {
Object target = new Object();
ReferenceQueue<Object> queue = new ReferenceQueue<>();
WeakReference<Object> weak = new WeakReference<>(target, queue);
SoftReference<Object> soft = new SoftReference<>(target);
PhantomReference<Object> phantom = new PhantomReference<>(target, queue);
try {
System.out.println("weak.get() == target: " + (weak.get() == target));
System.out.println("soft.get() == target: " + (soft.get() == target));
weak.clear();
soft.clear();
System.out.println("weak.get() == null: " + (weak.get() == null));
System.out.println("soft.get() == null: " + (soft.get() == null));
System.out.println("poll() after clear: " + queue.poll());
if (!weak.enqueue()) {
throw new IllegalStateException("Expected weak reference to be enqueued");
}
System.out.println("remove(1000) == weak: " + (queue.remove(1000) == weak));
System.out.println("phantom.get() == null: " + (phantom.get() == null));
if (!phantom.enqueue()) {
throw new IllegalStateException("Expected phantom reference to be enqueued");
}
System.out.println("remove() == phantom: " + (queue.remove() == phantom));
} finally {
Reference.reachabilityFence(target);
}
}
}Result
weak.get() == target: true soft.get() == target: true weak.get() == null: true soft.get() == null: true poll() after clear: null remove(1000) == weak: true phantom.get() == null: true remove() == phantom: true
The fence keeps `target` strongly reachable, and explicit `enqueue()` supplies an entry before each `remove` call. This demonstrates clearing versus queueing, not GC timing or timeout expiry.
Related lessons
- Java · Lesson 45 · Advanced · Version: 2