Java Reference
In-Depth Information
will not need that network connection. In such cases, you can code the
finalize()
method as a backup to free the
resources if they have not been freed yet. You can call the
finalize()
method programmatically when you know for
sure that the resources can be freed. The following
FinalizeAsBackup
class shows the skeleton of the code that uses
such a technique:
/* Template of a class that uses finalize() method as a backup to free resources */
public class FinalizeAsBackup {
/* Other codes go here */
SomeResource sr;
public void aMethod() {
sr = Obtain the resources here...;
/* Do some processing . . . */
/* Note the conditional freeing of resources */
if (some condition is true) {
/* Free resources here calling finalize() */
this.finalize();
}
}
public void finalize() {
/* Free the resources if they have not been freed yet */
if (resources not yet freed ) {
free resources now;
}
}
}
The
aMethod()
method of the class gets the resource and stores its reference in the
sr
instance variable.
Programmers call the
finalize()
method when they are sure they should free the resources. Otherwise, the garbage
collector will call the
finalize()
method and resources will be freed. Note that the
FinalizeAsBackup
class is a
template. It contains pseudocode to explain the technique. This class will not compile.
■
the moral of the story about using the
finalize()
method is to use it with care and use it only as a last resort
to free resources. You can use a
try-finally
block to free resources. the order in which objects are finalized is not
defined. For example, if object
obj1
becomes eligible for garbage collection before object
obj2
, it is not guaranteed
that
obj1
will be finalized before
obj2
. When an uncaught exception is thrown, the main program is halted. however,
an uncaught exception in a finalizer halts the finalization of only that object, not the entire application.
Tip
Object Resurrection
Someone is about to die. God asks him for his last wish. He says, “Give me my life back.” God grants his last wish and
he gets back his life. When he was about to die the second time God kept quiet and let him die without asking him
for his last wish. Otherwise, he would ask for his life repeatedly and he would never die. The same logic applies to an
object's finalization in Java. The call to the
finalize()
method of an object is like the garbage collector asking the
object for its last wish. Generally, the object responds, “I want to clean up all my mess.” That is, an object responds
to its
finalize()
method call by performing some cleanup work. It may respond to its
finalize()
method call by