Ad

Thursday 20 August 2009

Can we make an object ineligigle for Garbage collection by using finalize method

An object will become eligible for garbage collection,when its not referred by any reference variable.so when the object is garbage collected,the object memory will be claimed by the JVM.The object finalize method will be called before an object is garbage collected.

Lets come to our discussion.can we use this finalize method to make this object ineligible for garbage collection by passing this object to some reference.The answer is Yes,but only once.

Let says we have a object 'A' whose finalize method is overridden to pass the object reference to some other reference Variable.At some point during program execution,when an object 'A' doesn't not have any reference variable, it becomes eligible for garbage collection.when this object is about to garbage collected,object's finalize method is called.since in finalize method we have passed the this object to some reference variable,it become ineligible for garbage collection(As this object has been referred).At some later point when the same object does not have any reference ,it will again become eligible for garbage collection.But this time finalize method wont be called at the time of garbage collection.so the object will be garbage collected and the object memory will be claimed.

Hence finalize method will be called only once for any object before the garbage collection.Thus we can't make any object permanently ineligible for garbage collection not more than once by using finalize method.

2 comments: