Java Reference
In-Depth Information
The finalize() method in the Object class does not do anything. You need to override the method in your class.
The finalize() method of your class will be called by the garbage collector before an object of your class is destroyed.
Listing 7-13 has code for the Finalize class. It overrides the finalize() method of the Object class and prints a
message on the standard output. You can perform any cleanup logic in this method. The code in the finalize()
method is also called finalizer.
Listing 7-13. A Finalize Class That Overrides the finalize() Method of the Object Class
// Finalize.java
package com.jdojo.object;
public class Finalize {
private int x;
public Finalize(int x) {
this.x = x;
}
public void finalize() {
System.out.println("Finalizing " + this.x);
/* Perform any cleanup work here... */
}
}
The garbage collector calls the finalizer for each object only once. Running a finalizer for an object does not
necessarily mean that the object will be destroyed immediately after the finalizer finishes. A finalizer is run when the
garbage collector determines that no reference exists for the object. However, an object may pass its own reference
to some other part of the program when its finalizer is run. This is the reason that the garbage collector checks one
more time after it runs an object's finalizer to make sure that no references exists for that object and then it destroys
(de-allocates memory) the object. The order in which finalizers are run and the time at which they are run are not
specified. It is not even guaranteed that a finalizer will run at all. This makes it undependable for a programmer to
write cleanup logic in the finalize() method. There are better ways to perform cleanup logic, for example, using
a try-finally block. It is suggested not to depend on the finalize() method in your Java program to clean up
resources uses by an object.
Listing 7-14 contains code to test the finalizers for your Finalize class. You may get a different output when you
run this program.
Listing 7-14. A Test Class to Test Finalizers
// FinalizeTest.java
package com.jdojo.object;
public class FinalizeTest {
public static void main(String[] args) {
// Create many objects, say 20000 objects.
for(int i = 0; i < 20000; i++) {
new Finalize(i);
}
}
}
 
Search WWH ::




Custom Search