Witscale Test Center

6.9 The finalize() method


6.9 The finalize() method

You can do some clean up operations just before an object is garbage collected. These operations are known as finalization. A common use of finalization is to release resources held by the object. Just before an object is garbage-collected, the garbage collector executes that object’s finalize() method. This method is a member of the java.lang.Object class. Since every class has the Object class as its superclass, this method is automatically inherited in all the classes. You can override the finalize method in your class to perform any finalization necessary for objects of that class. Following code shows how the Car class can override the finalize() method.

 

class Car {

   protected void finalize() throws Throwable {

     System.out.println(“Garbage collecting the Car object. . . ");

   }

 }

 

Usually you don't have to worry about overriding the finalize method to cleanup memory as the garbage collector automatically releases the unreferenced memory resources. In rare cases, however, you may want to implement the finalize method to release resources, such as native resources, that are not under the control of the Java garbage collector.

Since you cannot be sure of when garbage collection takes place, you cannot be sure exactly when this method will be called. Therefore you should avoid writing programs for which the correctness depends upon the timely execution of this method. For example, if the finalize() method of an object releases a resource that is needed again later by the program, the resource will not be made available until the garbage collector has run the finalize() method. If the program needs the resource before the garbage collector has run to finalize the unreferenced object, then your program may not function as expected.

Though you can not be sure when finalize() method will be executed, you are assured that it will be called only once by the garbage collector. The garbage collector will only call the finalize()method on unreachable objects, but the irony is that you can make such unreachable object reachable in the finalize() method itself. Like any other instance method, it has an access to the reference to the current object (using this keyword). Therefore you can store this reference in an object reference variable that is reachable from root references. Then the object becomes reachable again and therefore becomes ineligible for garbage collection. The garbage collector will not delete it from the memory for the time being. But, this trick will not work to keep an object permanently in memory. Remember that finalize() method is called only once for any given object. So the second time when this object becomes unreachable, the garbage collector will notice that its finalize() has already been called and will garbage-collect the object right away.