Java Reference
In-Depth Information
reference to this object is a weak reference. When the weak references to a
weakly reachable object are cleared, the object becomes eligible for finaliza-
tion.(Apartfromthegarbagecollectorbeingmoreeagertocleanuptheweakly
reachable object, a weak reference is exactly like a soft reference.)
• An object is
phantom reachable
if it is neither strongly, softly, nor weakly
reachable,ithasbeenfinalized,anditisreferredtobysome
phantom reference
(areferencetotheobjectwherethereferenceisstoredina
PhantomRefer-
ence
object). The strongest reference to this object is a phantom reference.
• Finally, an object is unreachable, and therefore eligible for removal from
memory during the next garbage collection cycle, when it is not reachable in
any of the above ways.
Theobjectwhosereferenceisstoredina
SoftReference
,
WeakReference
,or
PhantomReference
object is known as a
referent
.
Reference and ReferenceQueue
TheReference APIconsistsoffiveclasseslocatedinthe
java.lang.ref
package.
Central to this package are
Reference
and
ReferenceQueue
.
Reference
istheabstractsuperclassofthispackage'sconcrete
SoftReference
,
WeakReference
, and
PhantomReference
subclasses.
ReferenceQueue
is a concrete class whose instances describe queue data struc-
tures.Whenyouassociatea
ReferenceQueue
instancewitha
Reference
subclass
object (
Reference
object, for short), the
Reference
object is added to the queue
when the referent to which its encapsulated reference refers becomes garbage.
Note
You associate a
ReferenceQueue
object with a
Reference
object by
passing the
ReferenceQueue
object to an appropriate
Reference
subclass con-
structor.
Reference
is declared as generic type
Reference<T>
, where
T
identifies the
referent's type. This class provides the following methods:
•
void clear()
assignsnulltothestoredreference;the
Reference
object
onwhichthismethodiscalledisnot
enqueued
(inserted)intoitsassociatedref-
erence queue (ifthere isanassociated reference queue). (The garbage collect-
orclearsreferencesdirectly;itdoesnotcall
clear()
.Instead,thismethodis
called by applications.)