Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

PhantomReference — phantom references

PhantomReference<T> supports notification of changes in an object's reachability without exposing it through get(). It works with ReferenceQueue; the example demonstrates deterministic, manual enqueueing.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

PhantomReference<T> ref = new PhantomReference<>(referent, queue);

PhantomReference<T> in java.lang.ref supports scheduling post-mortem cleanup. Unlike WeakReference and SoftReference, it cannot expose the referent through get() — that method always returns null. Its constructor accepts a referent and a ReferenceQueue<? super T>; a null queue means no queue notification.

When GC detects phantom reachability, it atomically clears the relevant group of phantom references and enqueues registered references immediately or later. The program must keep the PhantomReference itself reachable; queue registration does not do so. Store cleanup data separately, without a strong reference to the monitored object.

refersTo(obj) tests referent identity, while refersTo(null) detects clearing. Calling clear() alone does not enqueue the reference. By contrast, enqueue() clears it and adds it to its queue if possible; a manual call does not prove that GC has reclaimed memory.

The example deliberately uses enqueue() instead of waiting for GC. Reference.reachabilityFence(referent) keeps the referent strongly reachable through the demonstration, preventing a GC race. poll() retrieves the reference object, not its referent. This demonstrates queue mechanics, not a resource-cleanup implementation.

Examples

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;

public class Main {
    public static void main(String[] args) {
        Object referent = new Object();
        ReferenceQueue<Object> queue = new ReferenceQueue<>();
        PhantomReference<Object> ref = new PhantomReference<>(referent, queue);

        System.out.println(ref.get() == null);
        System.out.println(ref.refersTo(referent));
        System.out.println(ref.enqueue());
        System.out.println(ref.refersTo(null));
        System.out.println(queue.poll() == ref);
        System.out.println(queue.poll() == null);
        Reference.reachabilityFence(referent);
    }
}

Result

true
true
true
true
true
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources