Java Reference
In-Depth Information
Because all Java classes inherit from the Object class, the finalize() method can be invoked on all Java objects.
Any class can override and implement its own version of the finalize() method. The finalize() method serves as
a finalizer for Java objects. That is, the garbage collector automatically invokes the finalize() method on an object
before reclaiming the object's memory. Understanding the correct use of the finalize() method is key to writing a
good Java program, which manages resources other than the heap memory.
Let's first start with a simple example that demonstrates the fact that the finalize() method is called before an
object is garbage collected. Listing 11-2 defines a method finalize() in the Finalizer class.
Listing 11-2. Using the finalize() Method
// Finalizer.java
package com.jdojo.gc;
public class Finalizer {
// id is used to identify the object
private int id;
// Constructor which takes the id as argument
public Finalizer(int id){
this.id = id;
}
// This is the finalizer for the object. The JVM will call
// this method, before the object is garbage collected
public void finalize(){
// Just print a message indicating which object is being garbage
// collected. Print message when id is a multiple of 100
// just to avoid a bigger output.
if (id % 100 == 0) {
System.out.println ("finalize() called for " + id ) ;
}
}
public static void main(String[] args) {
// Create 500000 objects of the Finalizer class
for(int i = 1; i <= 500000; i++){
// Do not store reference to the new object
new Finalizer(i);
}
// Invoke the garbage collector
System.gc();
}
}
finalize() called for 5300
finalize() called for 6900
finalize() called for 7100
more output (not shown here)...
Search WWH ::




Custom Search