Name

PhantomReference<T>

Synopsis

This class represents a reference to an object that does not prevent the referent object from being finalized by the garbage collector. When (or at some point after) the garbage collector determines that there are no more hard (direct) references to the referent object, that there are no SoftReference or WeakReference objects that refer to the referent, and that the referent has been finalized, it enqueues the PhantomReference object on the ReferenceQueue specified when the PhantomReference was created. This serves as notification that the object has been finalized and provides one last opportunity for any required cleanup code to be run.

To prevent a PhantomReference object from resurrecting its referent object, its get( ) method always returns null, both before and after the PhantomReference is enqueued. Nevertheless, a PhantomReference is not automatically cleared when it is enqueued, so when you remove a PhantomReference from a ReferenceQueue, you must call its clear( ) method or allow the PhantomReference object itself to be garbage-collected.

This class provides a more flexible mechanism for object cleanup than the finalize( ) method does. Note that in order to take advantage of it, it is necessary to subclass PhantomReference and define a method to perform the desired cleanup. Furthermore, since the get( ) method of a PhantomReference always returns null, such a subclass must also store whatever data is required for the cleanup operation. ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.