Monday, May 16, 2011

Object destruction and the finalize method

The aim of destructor in any OOPs language is:

  1. Free up the memory (c++ suffer from memory allocation / deallocation)
  2. Clean up any other resources (like closing of open file stream)

Java take cares of all and hence there is no destructor in JAVA. (With the help of Garbage collection) but still if you want to perform some additional tasks, then you can use the finalize() method of java.

But, we can’t rely on finalize() as it depends on GC. Sometimes, GC may never be invoked during the lifetime of the program. A good idea is to implement a method, say cleanUp() which does, any special processing required, ofcourse, other than freeing up memory. The programmer should call this method at the approppriate place in the program. That is the only way to make sure your program works correctly.

Example code of finalize in java:

class HasFinalize{

public static int number_of_things = 0;
public String what;

public HasFinalize(String what) {
this.what = what;

protected void finalize () {

public class TestFinalize {
public static void main(String[] args)
Thing obj = new Thing("Test App");


The method call System.runFinalizersOnExit(true) guarantees that finalizer methods are called before Java shuts down. However, this method is inherently unsafe and has been deprecated. An alternative is to add "shutdown hooks" with the method Runtime.addShutdownHook—see the API documentation for details.


If a resource needs to be closed as soon as you have finished using it, you need to manage it manually. Supply a method such as dispose or close that you call to clean up what needs cleaning. Just as importantly, if a class you use has such a method, you need to call it when you are done with the object.

No comments:

Post a Comment