It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Reg. GC Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Reg. GC " Watch "Reg. GC " New topic

Reg. GC

Angela Narain
Ranch Hand

Joined: Apr 14, 2001
Posts: 327
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 ?
Valentin Crettaz
Gold Digger

Joined: Aug 26, 2001
Posts: 7610
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...
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform

[Blog] [Blogroll] [My Reviews] My Linked In
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
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
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
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:

I agree. Here's the link:
subject: Reg. GC
It's not a secret anymore!