Java Reference
In-Depth Information
If you decide to override finalize() , your object's subclass layer must give its
superclasslayeranopportunitytoperformfinalization.Youcanaccomplishthistaskby
specifying super.finalize(); asthelaststatementinyourmethod,whichthefol-
lowing example demonstrates:
@Override
protected void finalize() throws Throwable
{
try
{
// Perform subclass cleanup.
}
finally
{
super.finalize();
}
}
The example's finalize() declaration appends throws Throwable to the
method header because the cleanup code might throw an exception. If an exception
is thrown, execution leaves the method and, in the absence of try-finally, su-
per.finalize(); never executes. (I will discuss exceptions and try-finally in
Chapter 3 . )
To guard against this possibility, the subclass's cleanup code executes in a block
that follows reserved word try . If an exception is thrown, Java's exception-handling
logic executes the block following the finally reserved word, and su-
per.finalize(); executes the superclass's finalize() method.
The finalize() methodhasoftenbeenusedtoperform resurrection (makingan
unreferencedobjectreferenced),toimplementobjectpoolsthatrecyclethesameobjects
whentheseobjectsareexpensive(time-wise)tocreate(databaseconnectionobjectsare
an example).
Resurrection occurs when you assign this (a reference to the current object) to a
classorinstancefield(ortoanotherlong-livedvariable).Forexample,youmightspe-
cify r = this; within finalize() toassigntheunreferencedobjectidentifiedas
this to a class field named r .
Becauseofthepossibilityforresurrection,thereisasevereperformancepenaltyim-
posedonthegarbagecollectionofanobjectthatoverrides finalize() .You'lllearn
about this penalty and a better alternative to overriding finalize() in Chapter 4 .
Search WWH ::




Custom Search