How many times finalize method will be invoked? who invokes finalize() method in Java?


The finalize() method belongs to the Object class. Right before closing an object, the garbage collector makes sure that there are no more references to it and, calls the finalize() method on it.

Therefore, once you override the finalize() method in it, you can do all the cleanup activity like closing the resources like database connection, network connection, etc.

protected void finalize throws Throwable{}

It is invoked only once during the execution of a program.

Following are some notable points about the finalize method.

  • Since this method belongs the Object class, which is the super class of all the classes in java, you can override it from any class.

  • This is an empty method but you can override it by writing the code to perform require clean up activity.

  • It is recommended to use try catch around the cleanup code (closing connections etc.) written in the finalize() method.

  • It is allowed to call the finalize() method explicitly. It just gets executed like any other method.

  • When you call the finalize() method explicitly, if the garbage collector is currently executing it an unchecked exception will be raised.

  • In the same way When you call the finalize() method explicitly and in the middle of the execution when the garbage collector tries to call it an unchecked exception will be raised.

Example

 Live Demo

public class FinalizeExample{
   public void finalize(){
      System.out.println("finalize method is executed...");
   }
   public static void main(String args[]){
      FinalizeExample obj = new FinalizeExample();
      obj.finalize();
      System.gc();
   }
}

Output

finalize method is executed...

Updated on: 29-Jun-2020

806 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements