finalize Method in Java with Examples

In this article you will learn what is finalize method in java and its disadvantages in using.

Garbage collection in java is the process of reclaiming the heap memory by the garbage collector when there are no references found on that object.

There may be a requirement in which an object has to perform some action just before it is being garbage collected.

For example, if an object is holding some resources like file connection then it is recommended to make sure that these resources are closed before an object is garbage collected.

Because only reclaiming the memory used by an object would not ensure that the resources it held would be released.

To achieve this purpose Java provides a mechanism known as finalization through finalize() method.

finalize method in Java is called by the garbage collector on an object for reclaiming memory and cleaning up resources just before the object is garbage collected.

finalize method signature

finalize method in Java is a protected method in Object class. Its syntax is

protected void finalize() throws Throwable

Note that finalize() is deprecated method since java 9.

How to Use finalize() method

Below is the program to use finalize() method in any class.

public class Demo 
{
 
         
    @Override
    protected void finalize() throws Throwable
    {
        try
        {
            //release resources here
        } 
        catch(Throwable t) 
        {
            throw t;
        } 
        finally
        {
            super.finalize();
        }
    }
}

Execution of finalize() method is not guaranteed

Lets learn why execution of finalize method in java is not sure in program. I am using Runnable interface to make twe threads to check whether it is called or not.


public class FinalizeTest implements Runnable
{

    private void finalizeMethod() throws InterruptedException
    {
        try
        {
            System.out.println("Executing try block");
            throw new Exception();
        }
        catch(Exception e)
        {
            System.out.println("Executing catch block");
        }
        finally
        {
            System.out.println("Executing finally block");
        }
    }
 
    //Overriding the finalize method
    @Override
    protected void finalize() throws Throwable {
        System.out.println("Executing finalize block");
        super.finalize();
    }
 
    @Override
    public void run() {
        try {
        	finalizeMethod();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        for(int i=1;i<=2;i++)
        {
            new Thread(new FinalizeTest()).start();
        }
        }
}
##Output##
Executing try block
Executing try block
Executing catch block
Executing catch block
Executing finally block
Executing finally block

As you can see that the finalize method is not called by JVM after any of the thread execution.

How to force finalize method to execute

We can make finalize method to execute forcefully by using eitherΒ Runtime.getRuntime().runFinalization()Β or Runtime.runFinalizersOnExit(true).

But both methods have disadvantages.

Runtime.getRuntime().runFinalization() makes best effort to execute finalize() method but it is not guaranteed that it will be executed.

Runtime.runFinalizersOnExit(true) is deprecatedΒ  now because sometimesΒ it runs finalize() method on live objects too.

public static void main(String[] args) {
        for(int i=1;i<=2;i++)
        {
            new Thread(new FinalizeTest()).start();
            Runtime.runFinalizersOnExit(true);
        }
        }
##Output##
Executing try block
Executing try block
Executing catch block
Executing finally block
Executing catch block
Executing finally block
Executing finalize block
Executing finalize block

Disadvantages of using finalize in java

  1. Any exception thrown by finalize method is completely ignored by garbage collector thread and exception will not be propagated further, actuallyΒ it will not be logged in log files. So you will not be able to find any exception in program later on.
  2. Generally, when you call a constructor then all super class constructors will be invoked implicitly.But in case of finalize() method this is not followed i.e constructor chaining. Ideally parent class finalize method should be called but it does not happen.
  3. It decreases the performance of the program.

Frequently Asked Questions (FAQ)

Q. Can we call finalize method in Java?

finalize() method is similar like any other methods in Java. It can be called manually in Java same as other methods.
However, It has one special feature that it may get called by the JVM before the garbage collection of object.

Q. Why do we use finalize method in Java?

finalize method is used to perform clean up operations on an object before the garbage collection of object.

Q. Why finalize () method should be avoided?

There are several disadvantages of finalize method like it decreases the performance.

Q. How many times Finalize method is called?

The number is not guaranteed.

Conclusion

Techies, you have learned what is finalize method in java, how to use it in java program and its disadvantages.

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

Leave a Reply