Previous | Next | Trail Map | Reference Objects | All About Reference Objects

Reference Queues

A java.lang.ref.ReferenceQueue is a simple data structure onto which the garbage collector places reference objects when the reference field is cleared (set to null). You would use a reference queue to find out when an object becomes softly, weakly, or phantomly reachable so your program can take some action based on that knowledge. For example, a program might perform some post-finalization cleanup processing that requires an object to be unreachable (such as the deallocation of resources outside the Java heap) upon learning that an object has become phantomly reachable.

To be placed on a reference queue, a reference object must be created with a reference queue. Soft and weak reference objects can be created with a reference queue or not, but phantom reference objects must be created with a reference queue:

ReferenceQueue queue = new ReferenceQueue();
PhantomReference pr = new PhantomReference(object, queue);

Another approach to the soft reference example from the diagram on the previous page could be to create the SoftReference objects with a reference queue, and poll the queue to find out when an image has been reclaimed (its reference field cleared). At that point, the program can remove the corresponding entry from the hash map, and thereby, allow the associated string to be garbage collected.

ReferenceQueue q = new ReferenceQueue();
Reference r;
	
while((r = q.poll()) != null) {

    //Remove r's entry from hash map

}


Note: A program can also wait indefinitely on a reference queue with the remove() method, or for a bounded amount of time with the remove(long timeout) method.
Soft and weak reference objects are placed in their reference queue some time after they are cleared (their reference field is set to null). Phantom reference objects are placed in their reference queue after they become phantomly reachable, but before their reference field is cleared. This is so a program can perform post-finalization cleanup and clear the phantom reference upon completion of the cleanup.


Previous | Next | Trail Map | Reference Objects | All About Reference Objects