Java Reference
In-Depth Information
Table 11-1.
Constructors for the SoftReference, WeakReference, and PhantomReference classes
Class
Constructors
SoftReference
SoftReference(Object referent)
SoftReference(Object referent, ReferenceQueue q)
WeakReference
WeakReference(Object referent)
WeakReference(Object referent, ReferenceQueue q)
PhantomReference
PhantomReference(Object referent, ReferenceQueue q)
You can create objects of
SoftReference
and
WeakReference
classes using an object of any class, or using an
object of any class and an object of the
ReferenceQueue
class. You must create an object of the
PhantomReference
class using an object of any class and an object of the
ReferenceQueue
class. You can create an object of the
SoftReference
class as shown:
Employee john = new Employee ("John Jacobs");
SoftReference sr = new SoftReference(john);
The memory state after executing the above two statements is depicted in Figure
11-4
.
A strong reference
john
John Jacobs
X
sr
A soft reference (or a weak-
reference in general)
A SoftReference
object
X
A strong reference
Figure 11-4.
An example of a soft reference
In Figure
11-4
, there are two strong references and one weak reference. All three weak reference classes have two
instance variables:
referent
and
queue
. I will not discuss any other instance variables of these classes here. They are
used to hold the reference of the object and reference queue passed in to the constructors of these classes. A reference
to any object stored in the
referent
instance variable of any of these three classes is known as a weak reference in
general—and a soft reference, weak reference, or phantom reference in particular, depending on the class being used.
Therefore, the link from a soft reference object to the employee object shown in the figure is a weak reference. To be
specific, I will call it a soft reference because I used an object of the
SoftReference
class. Any reference that does not
involve the
referent
instance variable of any of these three classes is a strong reference in Java. Therefore,
john
and
sr
are strong references.