Hi everyone. I know that objects are not guaranteed to be garbage collected and thus their finalize methods are not guaranteed to be called. However, if an object IS going to be garbage collected (because the runtime system has decided it) is it guaranteed that at this point the object's finalize() method will be called (if it has not been called previously by the runtime system)???
Cowgirl and Author
Joined: Oct 10, 2002
Howdy -- yes it IS guaranteed that IF the GC decides to reclaim an object, that object's finalize() method WILL be called... but only (as you said) if the finalize() method has not already been called on this object. So if an object becomes eligible for GC (for the first time), and the GC decides to take it, finalize() is called. BUT... if in the finalize() method the object brings itself back to life (say, by passing a reference to itself out to some other object that keeps it alive), and then later becomes eligible AGAIN, the GC will never call finalize() again, even if it decides once again to reclaim the object. So finalize() is guaranteed to be called no more than ONCE per runtime. And it is NOT guaranteed to be called at all, UNLESS the GC *is* going to collect the object, and finalize() has not yet been called for that object. The guarantees are: 1) If an object is going to be collected, and finalize() has never been called, the GC WILL call finalize() before reclaiming it. 2) If an object becomes eligible, that does NOT mean the object will be selected for GC, so eligibility for GC does not automatically mean that finalize() will be called. 3) The finalize() method of an object will be called only ONCE per runtime, regardless of how many times the object becomes eligible for GC. 4) There is no guarantee that finalize() will be called prior to a JVM shutting down, of course. Just because an object becomes eligible does NOT mean the object will ever be collected. cheers, Kathy "Changing the heap, one object at a time."
Joined: Jan 13, 2003
Thank you for the thorough explanation !!! That was very helpful!