jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes finalize() question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "finalize() question" Watch "finalize() question" New topic

finalize() question

Sharda Vajjhala
Ranch Hand

Joined: Nov 14, 2001
Posts: 57
If the finalize() method of an object is re-references an object so that it becomes in-eligible for garbage collection

1) The compiler will throw an error.
2) The garbage collector "collects" the object anyway.
3) The garbage collector does not collect the object in the present sweep. But when the object becomes eligible for garbage collection again, its finalize method will not be called by the garbage collector (i.e., if the garbage collector gets a chance to run.). It will simply be garbage collected.
4) The object can never be garbage collected and hence leads to memory-leak. Each time the garbage collector calls finalize before "collecting" the object the object "resurrects" itself.

Answer is 3. Why? I thought it would be 4, since it is re-referencing the object whenever finalize()is called.
The API says that the finalize() is called only once, but what about cases like the above?
Also, can anyone explain the other kinds of common GC implementations, besides "mark and sweep"?
shweta mathur
Ranch Hand

Joined: Sep 23, 2002
Posts: 109
Sharda, just see if the following can throw light on ur issue.
First time when the object is de-refernced, it is eligible to be garbage collection. At that time, finalize method is called just before garbage collection.
In this case the object is re-refernced and so it is not garbage collected and again available in the program.
Next time again when the object is de-referenced, it is eligible to be garbage collected. But since finalize method will not be called the second time, so no chance of re-referncing. Therefore it will be garbage collected.
Also to know more abt Garbage collection like " stop-and copy) u can refer "Thinking in Java" by Bruce Eckel, Ch-4.

--Shweta<br />SCJP 1.4 <br />SCWCD
I agree. Here's the link: http://aspose.com/file-tools
subject: finalize() question
It's not a secret anymore!