devxlogo

Finalization and Cleanup

Finalization and Cleanup

Although Java does not provide a destructor as in C++, you can use an overridden finalize() method for similar purposes. The overridden finalize() method is invoked on an object before the garbage collector reclaims the memory occupied by the object. If the method named runFinalizersOnExit(true) is invoked, an overridden finalize() method will be invoked on every object of that type that still exists when the main method terminates. Although an overridden finalize() method is not as definitive as a C++ destructor, at least it assures cleanup of objects before the garbage collector reclaims the memory occupied by the object. Cleanup may involve closing sockets or other tasks not related to the reuse of memory. This code was tested using JDK1.1.6 under Win95:

   import java.util.*;import java.io.*;class Cleanup02 {	int myData;  	public static void main(String[] args){ //main method		System.runFinalizersOnExit(true);		Cleanup02 obj1 = new Cleanup02(1);		Cleanup02 obj2 = new Cleanup02(2);		System.out.println("Terminating program");	}//end main	//-----------------------------------------------------//	Cleanup02(int myData){//constructor		this.myData = myData;	}//end constructor	//-----------------------------------------------------//  	protected void finalize(){//override finalize method		System.out.println("Do cleanup for obj" + myData + 				" here");	}//end finalize()}//End Cleanup02 class.

This program produces the following output:

 Terminating programDo cleanup for obj1 hereDo cleanup for obj2 here

devx-admin

Share the Post: