Hi Ranchers, I have a doubt regarding garbage colletion and the finalize() method. It is known that the finalize() method is invoked on an object when it is garbage collected, and that the finalize() method is run only once on an object. If the finalize() method is overriden and the object is instead resurrected, then the next time the object needs to be garbage collected, the finalize() method WILL NOT be invoked on it. Correct? That means, it will be GONE (I am not using the term garbage collected), when it next is left simply dangling without a reference. Well, my real doubt now follows: In JQ+, I found a few questions like: "The finalize() method is ALWAYS called before an object is garbage collected, true or false". Answer is invariably TRUE. My answer is FALSE. What say you ranchers? Thanks a lot. Rahul
I agree with your explanation. But, Invoking finalize method before GCing on objects can be seen like this
it will be definitely called on non-resurrected objects before GCing & on resurrected objects it was already called once. On that basis can we say that finalize() method will be definitely called on object before GCing..
tvs sundaram already pointed it out. An object cannot be garbage collected twice. Indeed, once it is destoyed, it is destroyed. How can you destroy it again. Calling finalize and destroying an object are 2 diff. things. So, there is no such thing as "for the first time" because there is only one time! So the point is, if the object is actually being destroyed (ie. being garbage collected), finalize() method has already been called.
Wellllllll, I just re-read it - and it IS technically true. I guess it is just that we tend to think of finalize happening IMMEDIATELY before garbage collecting, and while that is USUALLY true, it is a mistake to think that it is ALWAYS true. So - Paul is right.
Yes the finalize will get called before being processed by the GC but this is not to say the finalize method will definitely get called. This is half question half statement. Am I correct with this? Joe
Joined: Sep 29, 2000
The finalize will ALWAYS get called exactly ONE time before the object is garbage collected (ie. destroyed - notice the past tense). That does NOT mean that the finalize will get called each time the garbage collector examines the object. *************** 1 object has no references 2 garbage collector examines object 3 garbage collector calls finalize on object 4 finalize resurrects object 5 object again has no references 6 garbage collector again examines object 7 finalize has ALREADY happened so garbage collector immeditately destroys object WITHOUT a second call to finalize.