Table of Contents

    Java finalize() Method: Usage and Best Practices

    Java finalize() Method: Usage and Best Practices

    If you don't know about Garbage Collection please read this first then come back to this topic

     Garbage Collection

    finalize() method

    Sometimes an object will need to perform some action when it is destroyed. For example closing an open connection or releasing any resources held. To handle such situations, Java provides a mechanism called finalization. finalize() method is called by garbage collection thread before collecting object. It is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing.

    Signature of finalize() method

    protected void finalize()
    {
     //finalize-code
    }

    Parameters

    NA

    Return Value

    This method does not return a value.

    Exception

    Throwable ? the Exception raised by this method

    Some Important Points to Remember

    1. The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).
    2. finalize() method is defined in java.lang.Object class, therefore it is available to all the classes.
    3. finalize() method is declare as proctected inside Object class.
    4. finalize() method gets called only once by a Daemon thread named GC (Garbage Collector)thread.

    gc() method

    The gc() method is used to invoke the garbage collector explicitly to perform cleanup processing. However gc() method does not guarantee that JVM will perform the garbage collection. It only request the JVM for garbage collection. This method is present in System and Runtime class.

    Example for gc() method

    Program:

    public class FgClass
    {
    
        public static void main(String[] args)
        {
            FgClass t = new FgClass();
            t=null;
            System.gc();
        }
        public void finalize()
        {
            System.out.println("Garbage Collected ");
        }
    }

    Output:

    Garbage Collected
    Press any key to continue . . .

    Simple Example of garbage collection in java

    Program:

    public class GarbageC{
    
     public void finalize(){
    	 System.out.println("object is garbage collected");
    	 }
    
     public static void main(String args[]){
      GarbageC s1=new GarbageC();
      GarbageC s2=new GarbageC();
      s1=null;
      s2=null;
      System.gc();
     }
    }

    Output:

    object is garbage collected
    Press any key to continue . . .

    Simple Example of finalize() in java

    The following example shows the usage of lang.Object.finalize() method.

    Program:

    import java.util.*;
    public class ObjectDemo extends GregorianCalendar {
    
       public static void main(String[] args) {
          try {
             // create a new ObjectDemo object
             ObjectDemo cal = new ObjectDemo();
    
             // print current time
             System.out.println("" + cal.getTime());
    
             // finalize cal
             System.out.println("Finalizing...");
             cal.finalize();
             System.out.println("Finalized.");
    
          } catch (Throwable ex) {
             ex.printStackTrace();
          }
       }
    }

    Output:

    compile and run the above program, this will produce the following result:

    Mon Aug 21 16:02:29 IST 2017
    Finalizing...
    Finalized.
    Press any key to continue . . .