All About Reference Objects |
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 tonull
). 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 }
Soft and weak reference objects are placed in their reference queue some time after they are cleared (their reference field is set to
Note: A program can also wait indefinitely on a reference queue with theremove()
method, or for a bounded amount of time with theremove(long timeout)
method.
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.
All About Reference Objects |