Tutorials

Java Memory Management


Finalize Method


As of now you must be aware that it is garbage collector which is responsible to free the memory space (heap) by collecting the garbage.

 

What is garbage?

  • object residing in memory having no reference,
  • available object reference is set to null.

Now before collecting the garbage (object) wouldn't it be sweet and intelligent move of garbage collector to allow the object to perform any necessary task, which it may be required to do, before it is collected.

 

This is where finalize() method plays its role.

 

Before the object is about to get collected by garbage collector, collector provides last opportunity to object by calling finalize() to perform any clean up activity such as closing any open connection or releasing the System resource (if held) or other necessary task.

 

The finalize() method is defined in java.lang.Object class and thus is available to all classes for overriding purpose.

Given below is the general format of finalize() .


protected void finalize( ) {

    //task to be performed before

    //object is garbage collected goes here

}

You can override finalize( ) and provide your code inside it which needs to be executed before the object is garbage collected.

 

Who calls finalize() method?

  • It is responsibility of Garbage collector to call finalize() once for an object. Always remember, Garbage collector calls finalize() only once. And if object somehow escapes from being garbage collected then finalize() is not going to be called again.
  • You can explicitly call finalize() if you want.To do so you can call Runtime.getRuntime().runFinalization() OR Runtime.runFinalizersOnExit(true)
  • It may also happen in many case that finalize() would not get called at all.

 

Disadvantage of garbage collector

1. The problem with finalize is that it is not guaranteed when it will be called by Garbage collector. It may also happen that it is not called. Even if it is called it is not guaranteed that object would get immediately collected.

 

So it is not recommended to put inside finalize() any critical code (for performing critical task). Because it is highly unreliable due to uncertainty of its execution behavior.

 

 



Please Share this page
Views : 82
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!