Wednesday 28 May 2014

Why not to use finalize () method in java

Why not to use finalize () method in java
Finalize ()  method is defined in java.lang.Object class.

Finalize () method is invoked by garbage collector before reclaiming the memory allocated to the object.

Finalize () method is the last chance for any object to perform any cleanup activity i.e. releasing any system resources held, closing any open connection etc.  But In general its best not to rely on finalize () method  to do any cleaning up etc. as execution of finalize() method is not guaranteed.

Problems in using finalize method or why finalize () method should not be used in your application:--

11.  Finalize () method execution is not guaranteed at all. It is not guaranteed that finalize () method will be executed or exactly when it will be executed. For example, an object may wait indefinitely after becoming eligible for garbage collection and before it’s finalized () method is called.  Similarly, even if finalize method is invoked by garbage collector, it does not guarantee that object will be immediately collected.

22.  Finalize () method invocation is not chained like constructors. If you are overriding finalize () method from super class, than it’s your responsibility to call finalize () method of super class. If you forget to invoke super class finalize () method, then finalize () of super class will never be invoked. So it becomes critical to remember this and provide an opportunity to finalize of super class to perform cleanup.

33.  Finalize ()  never runs more than once on any object. Finalize () method is called only once by garbage collector. If object revive itself from finalize method, than finalize () will not be called again.

44.  Any exception thrown by finalize method is ignored by GC thread and thrown exception will not be    propagated further.  

No comments:

Post a Comment