Well, that is true.
finalize()
method is being called when GC decides that the object should be deleted but it doesn't mean, that the object will be removed anyway right after finalize
finishes.
IT DOESN'T WORK THIS WAY:
_________________________
IF shouldBeRemoved(object)
object.finalize();
remove(object);
After finalize
executes, GC will check once more if the object should still be removed. To qualify for removal, an object shouldn't be referenced from any object that is reachable from the root objects.
IT WORKS THIS WAY
_________________
LABEL
IF shouldBeRemoved(object)
object.finalize();
IF shouldBeRemoved(object)
remove(object);
ELSE
GOTO LABEL
Let's imagine the following case:
class Foo {
Application a;
Foo(){};
@Override
public void finalize() {
this.a = Application.getInstance();
}
}
Where Application
is a class which represents the root object of the Application
. In this case, as a
is still reachable, the object of class Foo
that qualified for removal right before, has just resurrected.
IMPORTANT REMARK
You are not guaranteed, that the finalize
will be called, as it requires another object to take care of finalize
method being called, so in case there is no enough free space on the heap, object might be destroyed without calling finalize
.