Tag: use of finalize method in java

finalize method in Java

What is finalize() method in Java?

 

  • finalize( ) method is a method of Object class which is called just before the destruction of an object by the garbage collector.
  • After finalize( ) method gets executed completely, the object automatically gets destroyed.
  • The purpose of calling finalize method is to perform activities related to clean up, resource deallocation etc.

 

Prototype-

 

Rules for finalize() method-

 

Rule-01:

 

We can override finalize( ) method in our class based on our requirements to define our own clean up activities.

finalize( )
{
    // Clean up activities
    // Resource deallocation activities
}

 

Rule-02:

 

When garbage collector calls the finalize( ) method, it is called on that object which has to be destroyed and the finalize( ) method of corresponding class gets executed.

 

Example-

Consider the following program-

class Test
{
    public static void main(String[ ] args)                   // A "main thread" gets introduced
    {
        String s = new String("Gate Vidyalay");               // A String object gets created
        s = null;                                             // String Object becomes eligible for garbage collection
        System.gc( );                                         // A request is made to JVM for running garbage collector ; A "gc thread" gets introduced
        System.out.println("End of main method");
    }

    public void finalize( )                                   // Test class finalize( ) method
    {
        System.out.println("Finalize method of Test class");
    }
}

Output-

End of main method

 

Analysis-

 

  • In the above program, we first created a new String object and then made it eligible for garbage collection by nullifying its reference variable. We then requested the JVM to run the garbage collector for collecting the String object.
  • According to rule-02, because a String object has become eligible for garbage collection, so we expect the garbage collector to call String class finalize( ) method which is known to have empty implementation and not the finalize( ) method of Test class.
  • The output of the program clearly shows that the finalize( ) method of String class gets executed and not the finalize( ) method of Test class because the print statement of finalize( ) method of Test class does not get executed.

This justifies our rule-02.

 

Rule-03:

 

We can call the finalize( ) method explicitly based on our requirements.

If called explicitly, finalize( ) method will execute as a normal method and object will not be destroyed. The object will be destroyed only when the finalize( ) method is called by the garbage collector itself.

 

Example-

Consider the following program-

class Test
{
   public static void main(String[ ] args)         // A "main thread" gets introduced
   {
      Test t = new Test( );                        // A Test object gets created
      t.finalize( );                               // Finalize( ) method is called explicitly
      t = null;                                    // Test object becomes eligible for garbage collection
      System.gc( );                                // A request is made to JVM for running garbage collector ; A "gc thread" gets introduced
      System.out.println("End of main method");
   }

   public void finalize( )                         // Test class finalize( ) method
   {
      System.out.println("Finalize method called");
   }
}

Output-

There are two possible outputs-

Finalize method called
End of main method
Finalize method called

         OR

Finalize method called 
Finalize method called 
End of main method

 

Analysis-

 

  • In the above program, we first created a new Test object and then called the finalize( ) method explicitly which executed the finalize( ) method of Test class and “Finalize method called” got printed on the console but the object did not get destroy. This justifies our rule-03.
  • Then, we made the Test object eligible for garbage collection by nullifying its reference variable and then introduced a gc thread in the system which requested the JVM to run the garbage collector for collecting the Test object.
  • Then, two threads got introduced in the system- main thread and gc thread.
  • We can’t predict exactly which thread completes its execution first. So, two outputs are possible as shown.

 

Rule-04:

 

  • If finalize( ) method is called explicitly by the programmer and while executing that finalize( ) method if any kind of exception occurs which is uncaught i.e. no catch block is present to catch the exception, then the program will terminate abnormally by raising that exception.
  • If finalize( ) method is called by the garbage collector and while executing that finalize( ) method if any kind of exception occurs which is uncaught i.e. no catch block is present to catch the exception, then JVM will ignore that exception and rest of the program will be executed normally.

 

Example-

Consider the following program-

class Test
{
   public static void main(String[ ] args)
   {
      Test t = new Test( );                              // A Test object gets created
      t.finalize( );                                     // Statement-01 (say)
      t = null;                                          // Test object becomes eligible for garbage collection
      System.gc( );                                      // A request is made to JVM for running garbage collector
      System.out.println("End of main method");
   }

   public void finalize( )                               // Test class finalize( ) method
   {
      System.out.println("Finalize method called");
      System.out.println(10/0);                          // This statement gives rise to Arithmetic Exception
   }
}

 

Case-01: When statement-01 is not commented-

 

  • When statement-01 is not commented, t.finalize( ); statement remains active which calls the finalize( ) method explicitly.
  • Finalize( ) method tries to evaluate the expression 10/0 which gives rise to an arithmetic exception and program terminates by raising that exception as shown by the output.

 

Output-

finalize method called
"Exception in thread "main" java.lang.ArithmeticException: / by zero"

 

Case-02: When statement-01 is commented-

 

  • When statement-01 is commented, t.finalize( ); statement goes dead and thus no explicit call is made to the finalize( ) method.
  • Now, the arithmetic exception raised by the implicit call to finalize( ) method is ignored by the JVM and the rest of the program executes normally as shown by the output.
  • Two outputs are possible because two threads exist in the system – main thread and gc thread and these threads can complete their execution in any order.

 

Output-

finalize method called
End of main method

        OR

End of main method
finalize method called

 

Rule-05:

 

Garbage collector calls the finalize( ) method only once on any object even though that object becomes eligible for garbage collection multiple times.

 

Get more notes and other study material of Core Java.

Watch video lectures by visiting our YouTube channel LearnVidFun.