Monday 7 March 2016

finalize() method in java

As a java developer, you must be aware that it is garbage collector which is responsible to free the memory space ( heap) by collecting the 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. Here 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.

Other Key Points :

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.

2 comments:

  1. Good article keep posting...

    ReplyDelete
    Replies
    1. Thanks Mahesh for your appreciation. It really motivates :)

      Delete

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.