Java Reference
In-Depth Information
uses the information provided by the queue to remove all hashmap entries that no
be garbage collected. However, a queue associated with SoftReference can alert
the application that heap space is beginning to run low.
The PhantomReference class describes a Reference object whose referent is
phantom reachable. As well as inheriting Reference 's methods and overriding
get() ,thisgenericclassprovidesasingleconstructorforinitializinga PhantomRe-
ference object:
PhantomReference(T r, ReferenceQueue<? super T> q)
encapsulates r 's reference. The PhantomReference object behaves as a
phantomreferenceto r .The ReferenceQueue objectidentifiedby q isas-
sociatedwiththis PhantomReference object.Passing null to q makesno
sense because get() is overridden to return null and the PhantomRefer-
ence object will never be enqueued.
Although you cannot access a PhantomReference object's referent (its get()
methodreturnsnull),thisclassisusefulbecauseenqueuingthe PhantomReference
reclaimed.Thissignalletsyouperformcleanupwithoutusingthe finalize() meth-
The finalize() method is problematic because the garbage collector requires at
least two garbage collection cycles to determine if an object that overrides final-
ize() can be garbage collected. When the first cycle detects that the object is eli-
gibleforgarbagecollection,itcalls finalize() .Becausethismethodmightperform
resurrection (see Chapter 2 ), which makes the unreachable object reachable, a second
cycle slows down garbage collection.
If finalize() is not overridden, the garbage collector does not need to call that
only one cycle.
Although you cannot perform cleanup via finalize() , you can still perform
cleanup via PhantomReference . Because there is no way to access the referent
( get() returns null), resurrection cannot happen.
Search WWH ::

Custom Search