2
votes

I red from the following link:garbage collection from geeksforgeeks and here it is said that:

The finalize() method is never invoked more than once for any given object.

So, here it is said "more than once" and i'm wondering whether there is possibility that finalize() method is not invoked and garbage collector destroys that object.

Is it possible?

1
This might help.Andrew S
Your newly inserted block is wrong. Even if the garbage collectors runs, there is no guaranty that the finalize() method gets executed. The word “definitely” is inappropriate here. All the garbage collector does, is enqueuing objects needing finalization. One or more finalizer threads may process them, but the JVM might terminate before they get to a particular object. Further, a JVM is not required to support finalization at all.Holger
First, questions are not supposed to contain answers. Second, a wrong statement doesn’t become better when you repeat it underneath and say you made it simple. It’s not simple, it’s still wrong. And when you know that there is an already existing Q&A covering the topic better, you can just delete your question.Holger
Yes, please delete, unless you can make it much better and different from the linked answer.maaartinus
I think nobody has given attention to exact meaning of the question.my question is: assume that garbage collector is definitely going to be run to destroy a particular object in heap(that is object is definitely going to be destroyed by garbage collector) so is there any possibility that garbage collector fully destroyed the object in heap but didn't call the finalize() method on that object? And you all assumed that there is not certainity in the destroying of object by the garbage collector. Now is it clearer?Himanshu Roy

1 Answers

2
votes

When the GC has found an object with class where finalize() has been overridden it is added to a queue of objects to have finalize() called on them. It is only after the object has been finalized once, that the GC can clean it up. i.e. this would be on a later GC.

e.g. If an object is in tenured space, it might be found until a full collection is performed, and it will only be cleaned up on a full GC after the finalize method has been called.

For further details, this is the Java 11 Javadoc for Object.finalize()

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#finalize()

so is there any possibility that garbage collector fully destroyed the object in heap but didn't call the finalize() method on that object?

While the object is in the finalization queue, it can't be removed.

And you all assumed that there is not certainity in the destroying of object by the garbage collector.

It won't be destroyed while there is still a strong reference to it.