What is the Purpose of Finalize Method in Java ?

finalize method is a method of Object class. It is invoked by GC just before the destruction of an object. It is used to free all the system resources held by the object .

It must be overridden by a class in order to perform deallocation of resources of related objects. It is preceded with protected access specifier and doesn’t perform any special action. If there is an exception occurred it would be handled by throwable.

Syntax:

protected void finalize() throws Throwable 
{ 
}

When does Java finalize method come into the picture? [ A brief Article on GC ]

  • As we know object gets its memory in Heap and the variable reference to that object gets memory in the stack.
  • Each object gets spaces depending on their size.
  • When an object is no longer in use and present in heap memory, then that object becomes eligible for garbage collection
  • Garbage collector wipes up all unreachable objects and reclaims the occupied memory
  • Lastly, this reclaimed memory once again can be used.

Before destroying an object GC invokes finalize method with the purpose of resource deallocation and perform cleaning operation.

Finalize method & Finalization

It allows us to perform some action before destroying a particular object. There may be a situation where an object is holding some resources and it is needed to be freed before the object gets destroyed.

So, a process of releasing resources held by the unreachable object and invoked just before the object’s destruction is called finalization. This method invokes beforehand reclaiming an object.

protected void finalize() { 
// action 
}

Java finalize method example:

class Sample
{
  @Override protected void finalize ()
  {
    System.out.println ("I am in Finalize Method");
  }
}

public class FinalizeExample
{
  public static void main (String[]args)
  {
    Sample obj = new Sample ();
      obj = null;
      System.gc ();
  }
}

Output:

I am in Finalize Method

Leave a Reply