CKTIS / Java
ReferenceQueue — receiving reference objects
ReferenceQueue lets you retrieve registered reference objects after the garbage collector or an explicit enqueue() adds them. Learn the difference between nonblocking poll() and the blocking remove() variants.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
ReferenceQueue<T> queue = new ReferenceQueue<>();
Reference<? extends T> ready = queue.poll();
Reference<? extends T> next = queue.remove();
Reference<? extends T> timed = queue.remove(timeoutMillis);ReferenceQueue<T> in java.lang.ref receives reference objects, not the objects they refer to. A reference is registered with a queue when it is created. The garbage collector adds it after detecting the appropriate change in its referent's reachability. Registration alone does not keep the reference object alive: the application must keep it reachable while notification is needed.
ReferenceQueue.poll() removes and returns an available reference, or immediately returns null. ReferenceQueue.remove() waits indefinitely for an element. The remove(long timeout) variant waits up to the specified number of milliseconds and may return null; 0 means an indefinite wait, and a negative value causes IllegalArgumentException. Both remove variants may throw InterruptedException. The timeout provides no real-time guarantees. These methods return Reference<? extends T>.
The example uses a WeakReference with a null referent and explicit enqueue(), so it does not depend on garbage collection. enqueue() always clears the reference. If the reference has already been enqueued or was never registered with a queue, enqueue() returns false without inserting it. Otherwise, it adds the reference to its registered queue and returns true. clear() alone does not enqueue the reference. In the example, enqueue() returns true, so the subsequent remove() call does not have to wait for GC. Receiving a reference from the queue does not by itself prove that its referent's memory has been reclaimed.
Examples
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
public class ReferenceQueueDemo {
public static void main(String[] args) throws InterruptedException {
ReferenceQueue<Object> queue = new ReferenceQueue<>();
WeakReference<Object> ref = new WeakReference<>(null, queue);
System.out.println(queue.poll() == null);
System.out.println(ref.enqueue());
System.out.println(queue.remove() == ref);
System.out.println(queue.poll() == null);
}
}Result
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.