Monday, 20 January 2014

Using finalize() method in java

The finalize() method:


finalize method in java is a special method much like main method in java. finalize() is called before Garbage collector reclaim the Object, its last chance for any object to perform cleanup activity i.e. releasing any system resources held, closing connection if open etc.The intent is for finalize() to release system resources such as open files or open sockets before getting collected.
Main issue with finalize method in java is its not guaranteed by JLS that it will be called by Garbage collector or exactly when it will be called, for example an object may wait indefinitely after becoming eligible for garbage collection and before its finalize() method gets called. similarly even after finalize gets called its not guaranteed it will be immediately collected.finalize method is called by garbage collection thread before collecting object and if not intended to be called like normal method.finalize method is called by garbage collection thread before collecting object and if not intented to be called like normal method.

Let’s look at syntax of finalize() method

protected void finalize()
{
//finalize code here;

}


Example for finalize method


// Using finalize() to detect an object that hasn't been properly cleaned up
class Book
 {
 boolean checkedOut = false;

 Book(boolean checkOut) 

{
 checkedOut = checkOut;
  }
void checkIn() {
 checkedOut = false;
  }

 public void finalize() 

{
 if (checkedOut)

 System.out.println("Error: checked out");
  }
}
public class TerminationCondition
 {
  public static void main(String[] args)
 {
  Book novel = new Book(true);
   
 novel.checkIn();
// Proper cleanup:
    
new Book(true);
// Drop the reference, forget to clean up:
    

System.gc();
// Force garbage collection & finalization:
  }
}


No comments:

Post a Comment