May 5, 2022

finalize() Method in Java

finalize() method in Java is a callback method which is called before any object is garbage collected.

What does finalize() method do

When there are no existing references to an object it is eligible for garbage collection. At the time of garbage collection the memory of an unreferenced object is reclaimed. But reclaiming the object memory does not guarantee that the resources it holds will be released.

That’s what finalize() method in Java can do, you can provide code in finalize() method to free up system resources like I/O stream, open DB or socket connection or to perform other cleanup. It will be executed just before the object is garbage collected.

finalize() method is part of Object class

finalize() method is present in the Java Object class, so it is available to all the classes in Java. Though the finalize method of class Object performs no special action; it simply returns normally. You will have to override finalize() method in your class and provide the required implementation for cleaning up.

The finalize() method of the Object class is as follows-

protected void finalize() throws Throwable { }

finalize() method is not reliable

The finalize() method may be called automatically by the system, but when it is called, or even if it is called, is uncertain. It may happen that the object is not immediately garbage collected even if it becomes eligible for garbage collection. Therefore, you should not rely on this method to do your cleanup for you.

In fact finalize() method is deprecated from Java 9 because of its being inherently problematic. For cleaning up it is better to use finally block or try-with-resources rather than relying on finalize() method.

How to use finalize() method in Java

Finalizer invocations are not automatically chained, unlike constructors, which means from finalize() method of the subclass, finalize method of the super class won't be called automatically. If a subclass overrides finalize it must invoke the super class finalizer explicitly.

Here note that finalize method is in Object class it means that the finalize method for any class can always invoke the finalize method of its super class.

Also finalize() method of the super class must be called from the finally block to ensure that super.finalize() is always called even if any exception disrupts the normal flow.

@Override
protected void finalize() throws Throwable {
  try {
    ... // cleanup subclass state
  } finally {
    super.finalize();
  }
}

finalize() method Java example

Here is a Java example where an object is created and then set to null which means object has no reference and it is eligible for garbage collection. Also calling System.gc() explicitly to run garbage collector.

public class FinalizeDemo {
  public static void main(String[] args) {
    // creating object
    FinalizeDemo finalizeDemo = new FinalizeDemo();
    // explicitly setting object reference as null so it is 
    // eligible for garbage collection
    finalizeDemo = null;
     
    // Calling System.gc() to run garbage collector
    System.gc();    
  }
	
  @Override
  protected void finalize() throws Throwable {
    try{
      System.out.println("finalize method called");
    }finally{        
      super.finalize();
    }
  }
}
Output
finalize method called

Exception in finalize() method

If any exception is thrown by the finalize method it will cause the finalization of this object to be halted, but is otherwise ignored.

Important points about Finalize

  1. finalize() method in Java is provided in the Object class.
  2. The finalize() method of the Object class has no implementation, it simply returns.
  3. finalize() method is invoked when the object is about to be garbage collected.
  4. The finalize method is never invoked more than once by a Java virtual machine for any given object.
  5. If a subclass overrides finalize it must invoke the super class finalizer explicitly using super.finalize().
That's all for the topic finalize() Method in Java. If something is missing or you have something to share about the topic please write a comment.
You may also like

No comments:

Post a Comment