Monday 24 March 2014

finalize() : Perform clean up operations

Before an object is garbage collected, the run time system calls its finalize() method. A subclass overrides the method to dispose of system resources or to perform other cleanup.

The method defined in Object class performs no action, Usually it is the sub classes which implements the functionality of finalize.

This method is never invoked more than once by a Java virtual machine for any given object.

It is a good practice to called the super class finalize method, inside the finalize method.

Let file “input.txt” contains “Hi How are You”

import java.io.*;
class FileReadEx{
 static FileInputStream fin;
 
 static{
  try{
   fin = new FileInputStream("input.txt");
  }
  catch(Exception e){
  }
 }
 
 void readData()throws Exception{
  int a;
  while((a=fin.read()) != -1){
   System.out.print((char)a);
  }
  System.out.println();
 }
 
 public void finalize()throws Throwable{
  super.finalize();
  System.out.println("Calling finalize method ");
  fin.close();
  System.out.println("Resource f1 is closed");
 }
 
 public static void main(String args[])throws Exception{
  FileReadEx obj1 = new FileReadEx();
  
  obj1.readData();
  obj1 = null;
  Runtime.getRuntime().gc(); 
  Thread.sleep(3000);
 }
}

Output
Hi How are You
Calling finalize method
Resource f1 is closed

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment