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
See also  lenso.ai - an AI reverse image search platform
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist