CKTIS / Java
Reference: get(), clear(), and reachabilityFence()
Reference provides operations on reference objects. Learn referent retrieval, reference clearing, and strong-reachability control in Java SE 21.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
T value = ref.get();
ref.clear();
Reference.reachabilityFence(owner);java.lang.ref.Reference<T> is the abstract base for reference objects; use subclasses such as WeakReference rather than extending it directly.
For a WeakReference, Reference.get (ref.get()) returns a strong reference to the referent if it is still available, or null otherwise. In Java SE 21, PhantomReference.get() always returns null, even before the reference is cleared. Reference.clear (ref.clear()) clears the reference without enqueueing it.
Reference.reachabilityFence(owner) keeps owner strongly reachable at least through the call; it does not trigger GC. Place it after protected operations, in finally, to cover exceptions too. Pass the referent, not the Reference object; passing null has no effect.
Examples
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
public class ReferenceDemo {
public static void main(String[] args) {
Object owner = new Object();
Reference<Object> ref = new WeakReference<>(owner);
try {
System.out.println(ref.get() == owner);
ref.clear();
System.out.println(ref.get() == null);
} finally {
Reference.reachabilityFence(owner);
}
}
}Result
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.