Finalize Method in Java – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 27 Dec 2020 15:52:23 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg Finalize Method in Java – Programmerbay https://programmerbay.com 32 32 What is the Purpose of Finalize Method in Java ? https://programmerbay.com/what-is-the-purpose-of-finalize-method-in-java/ https://programmerbay.com/what-is-the-purpose-of-finalize-method-in-java/#respond Thu, 09 Jul 2020 11:06:03 +0000 https://www.programmerbay.com/?p=4192 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

]]>
https://programmerbay.com/what-is-the-purpose-of-finalize-method-in-java/feed/ 0