finalize method is not working
class Abc
{
protectedvoid finalize()throws Throwable
{
System.out.println("Inside finalize");
super.finalize();
}
}
publicclass Finalize1
{
publicstaticvoid main(String args[])
{
Abc a=new Abc();
System.gc();
}
}
"Inside finalize" inside the finalize method is not getting printed.When the code ends won't the objects get garbage collected when the program ends.So shouldn't that statement get printed?
[1075 byte] By [
psychica] at [2007-11-26 18:11:52]

> a=null will work
As the API for System.gc() states:
Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.
Note the language: "suggests", "a best effort". This is not the same as a guarantee that the object will be collected and its finalize run.
> So a=null means till it has a null reference the
> object instance is not ready to be garbage collected?
Nothing can be GCed until it is unreachable. If your reference "a" is not null (god, I hate one-letter variable names) then the object it points to is reachable.
The first half of this article explains it.
http://java.sun.com/developer/technicalArticles/ALT/RefObj/
> Nothing can be GCed until it is unreachable.
Note that I'm not contradicting what the good DrLJ is saying. He's also correct.
So...
* Initially, your object could not possibly be GCed because it was reachable through the "a" reference.
* Even after setting a to null, thereby making the object unreachable, there's no guarantee it will ever be GCed with the code you have. You could create a crapload of objects and stuff them into a List until you get OutOfMemoryError. GC will run before that error occurs.