17.5.1. The Reference Class
The classes for the reference object types are contained in the package java.lang.ref. The primary class
is the generic, abstract class Reference
has four methods:
public Tget()
Returns this reference object's referent object.
public voidclear()
Clears this reference object so it has no referent object.
public booleanenqueue()
Adds this reference object to the reference queue with which it is registered,
if any. Returns TRue if the reference object was enqueued and false if
there is no registered queue or this reference object was already enqueued.
public booleanisEnqueued()
Returns true if this reference object has been enqueued (either by the
programmer or the garbage collector), and false otherwise.
We defer a discussion of reference queues until Section 17.5.3 on page 459.
Subclasses of Reference provide ways to bind the referent object to the reference objectthe existing
subclasses do this with a constructor argument. Once an object has been wrapped in a reference object you
can retrieve the object via get (and thus have a normal strong reference to it) or you can clear the reference,
perhaps making the referent unreachable. There is no means to change the object referred to by the reference
object and you cannot subclass Reference directly.
17.5.2. Strengths of Reference and Reachability
In decreasing order of strength, the kinds of reference objects available to you are SoftReference
WeakReference
object can pass through:
An object is strongly reachable if it can be reached through at least one chain of strong references (the
normal kind of references).
•
An object is softly reachable if it is not strongly reachable, but is reachable through at least one chain
containing a soft reference.
•
An object is weakly reachable if it is not softly reachable, but is reachable through at least one chain
containing a weak reference.
•
An object is phantom reachable when it is not weakly reachable, has been finalized (if necessary), but
is reachable through at least one chain containing a phantom reference.
•
- Finally, an object is unreachable if it is not reachable through any chain.
Once an object becomes weakly reachable (or less), it can be finalized. If after finalization the object is
unreachable, it can be reclaimed.
Objects need not actually go through all these stages. For example, an object that is reachable only through