Finalization

Finalization
  • Just before destroying an object, Garbage Collector calls finalize() method on the object to perform cleanup activities. Once finalize() method completes, Garbage Collector destroys that object.
  • finalize() method is present in Object class with following prototype.
    protected void finalize() throws Throwable
    
    Based on our requirement, we can override finalize() method for perform our cleanup activities like closing connection from database.
  • Note :
    1. The finalize() method called by Garbage Collector not JVM. Although Garbage Collector is one of the module of JVM.
    2. Object class finalize() method has empty implementation, thus it is recommended to override finalize() method to dispose of system resources or to perform other cleanup.
    3. The finalize() method is never invoked more than once for any given object.
    4. If an uncaught exception is thrown by the finalize() method, the exception is ignored and finalization of that object terminates.
  • // Java program to demonstrate requesting
    // JVM to run Garbage Collector
    public class Test
    {
        public static void main(String[] args) throws InterruptedException
        {
            Test t1 = new Test();
            Test t2 = new Test();
             
            // Nullifying the reference variable
            t1 = null;
             
            // requesting JVM for running Garbage Collector
            System.gc();
             
            // Nullifying the reference variable
            t2 = null;
             
            // requesting JVM for running Garbage Collector
            Runtime.getRuntime().gc();
         
        }
         
        @Override
        // finalize method is called on object once
        // before garbage collecting it
        protected void finalize() throws Throwable
        {
            System.out.println("Garbage collector called");
            System.out.println("Object garbage collected : " + this);
        }
    }
        Output:
        Garbage collector called
        Object garbage collected : Test@46d08f12
        Garbage collector called
        Object garbage collected : Test@481779b8
        
      Note :
      1. There is no guarantee that any one of above two methods will definitely run Garbage Collector.
      2. The call System.gc() is effectively equivalent to the call : Runtime.getRuntime().gc()

Comments