Tuesday, 3 November 2015

finalize() method

The java.lang.Object.finalize() is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

A subclass overrides the finalize method to dispose of system resources or to perform other cleanup activity i.e. releasing any system resources held, closing connection if open etc.

Main issue with finalize method, finalize () execution is not guaranteed at all.

Points to remember about finalize() method

1) finalize() method is defined as protected in java.lang.Object class.

2) finalize() method is not automatically chained like constructors.

If developer is overriding finalize method then it's developer responsibility to call finalize() method of the superclass, otherwise finalize() method of super class will never be called (super class to perform cleanup).

@Override
protected void finalize() throws Throwable {
     try {
           System.out.println("Finalize of Sub Class");
           //release resources, perform cleanup ;
     } catch(Throwable t) {
           throw t;
     } finally {
           System.out.println("Calling finalize of Super Class");
           super.finalize();
     }
}

3) finalize() method is called by garbage collection thread before collecting object and if not intended to be called like a normal method.

4) finalize() gets called only once by GC thread if object revives itself from finalize method than finalize will not be called again.

5) Any Exception is thrown by finalize method is ignored by GC thread and it will not be propagated further.


6) There is one way to increase the probability of running of finalize method by calling System.runFinalization() and Runtime.getRuntime().runFinalization().

These methods put more effort that JVM call finalize() method of all object which are eligible for garbage collection and whose finalize has not yet called. It's not guaranteed, but JVM tries its best.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...