Java Reference
In-Depth Information
A strong reference
john
X
John Jacobs
Figure 11-2.
An example of a strong reference
If at least one strong reference to an object exists, the garbage collector will not reclaim that object. In the
previous section, I discussed the object state based on its reachability. By stating that there is a strong reference to an
object, I mean that the object is reachable. With the introduction of weak references, now there are three more states
of an object based on its reachability:
•
Softly reachable
•
Weakly reachable
•
Phantom reachable
Therefore, when I called an object
reachable
in the last section, I will call it
strongly reachable
now onwards. This
change in terminology is because of the introduction of three new kinds of object reachability. Before I discuss the
three new kinds of object reachability, you need to know about the classes included in
java.lang.ref
package. There
are four classes of interest, as shown in Figure
11-3
. I will not discuss the
Reference
class from the diagram.
Figure 11-3.
A class diagram for some classes in the java.lang.ref package
The
Reference
class is the superclass for the
SoftReference
,
WeakReference
, and
PhantomReference
classes.
The
Reference
class is an abstract class. Therefore, you cannot create an object of this class. The
SoftReference
,
WeakReference
, and
PhantomReference
classes are used to create weak references. Note that by the phrase “weak
reference,” I mean a reference that is not a strong reference. By the phrase
WeakReference
, I mean the class
java.lang.ref.WeakReference
. I will describe a weak reference later in this section. The
ReferenceQueue
class is
used to place the references of
SoftReference
,
WeakReference
, and
PhantomReference
objects in a queue. Let's look
at different ways to create these three types of objects. The constructors for these three classes are shown in Table
11-1
.