CKTIS / Java
WeakReference — a weak reference to an object
WeakReference<T> holds a weak reference that does not prevent the garbage collector from reclaiming an object. Reading it through get() may return null; clear() clears the reference without destroying the object itself.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
WeakReference<T> ref = new WeakReference<>(referent);
// Alternative: WeakReference<T> ref = new WeakReference<>(referent, queue);
T value = ref.get();
ref.clear();WeakReference<T> in java.lang.ref does not keep its referent alive as a strong reference does. When the garbage collector determines that an object is weakly reachable, it clears the corresponding weak references. A typical use is canonicalizing mappings that must not keep objects alive.
The WeakReference(referent) constructor registers no queue; WeakReference(referent, queue) optionally registers a ReferenceQueue. GC-cleared references enter their registered queue at the same time or later. Clearing a reference does not itself mean that the object's memory has been reclaimed.
Inherited get() returns the object or null. Read the result once into a local variable and check it before use: a non-null result is a strong reference. clear() clears the reference but neither enqueues it nor destroys the object.
The example deliberately calls clear() instead of waiting for GC. Reference.reachabilityFence(value) keeps value strongly reachable until that point, making the output deterministic.
Examples
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
public class Main {
public static void main(String[] args) {
Object value = new Object();
WeakReference<Object> ref = new WeakReference<>(value);
System.out.println(ref.get() == value);
ref.clear();
System.out.println(ref.get() == null);
System.out.println(value != null);
Reference.reachabilityFence(value);
}
}Result
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.