问题
In an interview i was asked,suppose JVM runs gc when object of class A is not in used.
class A{
//some code here
protected void finalize(){
//code here
}
}
does it guarantee the execution of finalize(). I said yes
The next ques was if obj of Class A is being used, if now JVM runs GC does it execute finalize(). I said no, it'll not execute this finalize() as JVM does not collect A's object.
However she did not comment anything but looked disappointed.
Does i interpret it wrong? Thanks in Advance
回答1:
According to Bruce Eckel:
In Java, Objects do not always get garbage collected.
It generally means, that even if you declare your finalize()
method, it might never be called. In this case your cleanup routine will never be executed. It is all up to JVM GC.
Even though GC might run, it might not collect the given object. And as long as the Object, which is not referenced anymore, is still not collected, its finalize()
is never called.
Moreover, before the termination of the program, the garbage collection might not be called at all. In this case the memory is returned to the operating system as a whole, without any GC. And without any finalization method calls.
So, the answer to the first question of yours is no.
Your second answer was right. If the object is still in use, no matter if GC runs, it cant be collected (and finalize()
called), unless you use WeakReference
or something like that.
回答2:
There is no guarantee that a class finalize() method will be called.
The general contract of finalize is that it is invoked if and when the JavaTM virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class which is ready to be finalized
回答3:
Finalize method is never guaranteed to be called. See When is the finalize() method called in Java? for a good summary of this.
回答4:
There is no guarantee that finalize()
method will ever be called. Moreover, you can "revive" a component by assigning a link to it in the finalize()
method and it will prevent the garbage collection. Funny thing is that the finalize()
will never be invoked for this object ever again, even if it's garbage collected.
The second part of the question: if the object is used, then it will not be garbage collected and hence the finalize()
will not be called.
来源:https://stackoverflow.com/questions/20177580/when-finalize-is-being-executed