Java : Garbage Collection finalize() method example and uses

finalize() is an Object class method that is called by Garbage Collector just before deleting/destroying the object which is eligible for garbage collection before clean-up activity. Clean-up activity means closing the resources associated with that object like Database Connection, Network Connection or we can say resource de-allocation.

Points to Remember:

  • finalize() is a method not reserved keyword.
  • If finalize() method call manually by object instance then it will treat as normal method;
  • Once finalize() method completes immediately Garbage Collector destroy that object.
  • There is no guarantee about the time when finalizing () method is called. It may be called any time after the object is not being referred anywhere (can be garbage collected).

Syntax  of finalize() method:


protected void finalize throws Throwable{}

Since Object is the superclass of all the classes and finalize() is the Object class method hence finalize() method is available for every java class hence Garbage Collector can call finalize method on any java object. We also override this finalize() method for code clean-up activities.

finalize() method Example

In this example first calling finalize() method manually by test object which will behave as a normal method. For checking how Garbage collector call finalize() method setting test as null make object as unreferenced to make eligible for garbage collection. Here calling System.gc() to request JVM to call the garbage collector method. Now it’s up to JVM to call Garbage Collector or not. Usually, JVM calls Garbage Collector when there is not enough space available in the Heap area or when the memory is low.

public class FinalizeMethodTest {

	public static void main(String[] args) {
		FinalizeMethodTest test=new FinalizeMethodTest();
		//manually calling finalize method is call like normal method
		test.finalize();

		//unreferenced object to make eligible for garbage collector
		test=null;

		//Requesting JVM to call Garbage Collector method
		System.gc();

		System.out.println("Main Method Completed !!");
	}
	@Override
	 public void finalize()
	    {
	        System.out.println("finalize method overriden");
	    }
}

Output


finalize method overriden
Main Method Completed !!
finalize method overriden

Here finalize() method calls two times one for manually another by garbage collector for cleaning up this test object.

Exception Handling in finalize() method

If any exception happens in the finalize method then if we calling finalize manually then we have to handle it otherwise program will terminate abnormally. If finalize() method called by Garbage collector and then any unchecked exception happen then JVM will take care of it and the program will not terminate.

public class FinalizeMethodTest {

public static void main(String[] args) {
FinalizeMethodTest test=new FinalizeMethodTest();
//manually calling finalize method is call like normal method
try
{
test.finalize();
}
catch(Exception ex)
{
ex.printStackTrace();
}

//unreferenced object to make eligible for garbage collector
test=null;

//Requesting JVM to call Garbage Collector method
System.gc();

System.out.println("Main Method Completed !!");
}
@Override
public void finalize()
{
System.out.println("finalize method overriden");
//Exception occured here
System.out.println(10 / 0);
}<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
}

Output


finalize method overriden
java.lang.ArithmeticException: / by zero
    at classes.ObjectClass.FinalizeMethodTest.finalize(FinalizeMethodTest.java:30)
    at classes.ObjectClass.FinalizeMethodTest.main(FinalizeMethodTest.java:10)
Main Method Completed !!
finalize method overriden

In this example, we have to handle exception explicitly while calling finalize() method manually while calling by Garbage Collector no exception thrown.

Conclusion

In this blog, we learn about finalize() method calling manually and by Garbage Collector. Also, see by example to handle exception for both cases.