An object that has been eligible for GC may stop being eligible and return to normal life. This occurs if the call to the finalize() method re-establishes a reference from the active part of the program to the object. Can some explain me the lines marked in bold. Or how can explain with an example as to how we can re-surrect a object ?
Hi Angela, that means that in the finalize method (which is a method like anyone else) you may reassign a reference to "this" to a reference variable that may point to "this", and this would, roughly, resurrect the object and prevent it from being gced...
which means that when a Test2 object will be gced, its finalize method reassigns a reference to itself to another reference (refToTest2) in another class (Test1) and the Test2 object that was to be gced is now reachable from an active part again... I don't know if I'm clear with this explanation... The code doesn't work as is, but it shows how you may resurrect an object... HIH ------------------ Valentin Crettaz Sun Certified Programmer for Java 2 Platform
This code shows how the instance of Test3 is not gc.ed if finalize resurrect it: <br /> C:\Java\TIJ2\Test>java -verbose:gc Test3 [GC 158K->95K(1984K), 0.0077423 secs] Calling gc first time [Full GC 878K->877K(2040K), 0.0309416 secs] Doing finalization to Test3@273d3c Calling gc second time [Full GC 880K->877K(2040K), 0.0294766 secs] Here the second run of the gc only shows 880->877 But if you comment the last line in finalize: C:\Java\TIJ2\Test>java -verbose:gc Test3 [GC 158K->95K(1984K), 0.0078949 secs] Calling gc first time [Full GC 878K->877K(2040K), 0.0311327 secs] Doing finalization to Test3@273d3c Calling gc second time [Full GC 877K->95K(2040K), 0.0301128 secs] The gc shows 877->95
SCJP2. Please Indent your code using UBB Code
Joined: Jul 03, 2001
From the finalize API: " After the finalize method has been invoked for an object, no further action is taken until the Java virtual machine has again determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, including possible actions by other objects or classes which are ready to be finalized, at which point the object may be discarded. "
This code only shows the gc cleaning Test3 instance if both lines are commented: