Java Reference
In-Depth Information
The
main()
method first creates a
ReferenceQueue
object describing a queue
onto which a
PhantomReference
object that initially contains a
LargeObject
reference will be enqueued.
main()
next creates the
PhantomReference
object, passing a reference to a
newlycreated
LargeObject
objectandareferencetothepreviouslycreated
Refer-
enceQueue
object to the constructor.
After creating a byte array that's used to demonstrate
PhantomReference
,
main()
enters a polling loop.
The polling loop begins by calling
poll()
to detect the finalization of the
LargeObject
object. As long as this method returns null, meaning that the
LargeObject
objectisstillunfinalized,theloopoutputsamessageanddoublesthe
size of the byte array.
At some point, heap space will exhaust and the garbage collector will attempt to
obtain sufficient memory, by first clearing the
PhantomReference
object's
LargeObject
referenceandfinalizingthe
LargeObject
objectpriortoitsremoval
fromtheheap.The
PhantomReference
objectisthenenqueuedontothe
rq
-refer-
enced
ReferenceQueue
;
poll()
returns the
PhantomReference
object.
main()
now exits the loop, outputs a message confirming the large object's final-
ization, and outputs
pr.get()
's return value, which is null proving that you cannot
accessa
PhantomReference
object'sreferent.Atthispoint,anyadditionalcleanup
operations related to the finalized object (such as closing a file that was opened in the
file's constructor but not otherwise closed) could be performed.
Compile
Listing 4-9
and run the application. You should see output that's similar to
that shown here:
waiting for large object to be finalized
waiting for large object to be finalized
waiting for large object to be finalized
waiting for large object to be finalized
waiting for large object to be finalized
large object finalized
pr.get() returns null
Note
For a more useful example of
PhantomReference
, check out Keith D
Gregory's “Java Reference Objects” blog post (
http://www.kdgregory.com/