什么时候执行finalize

什么时候执行finalize

本文介绍了什么时候执行finalize()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一次采访中我被问到,假设当A类对象未被使用时JVM运行gc。

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
}
}

它是否保证执行finalize()。我说是的

does it guarantee the execution of finalize(). I said yes

下一个问题是如果正在使用类A的obj,如果现在JVM运行GC它是否执行finalize()。我说不,它不会执行这个finalize(),因为JVM不会收集A的对象。

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

推荐答案

根据Bruce Eckel的说法:

According to Bruce Eckel:

In Java, Objects do not always get garbage collected.

通常意味着,即使您声明 finalize()方法,它可能永远不会被调用。在这种情况下,您的清理例程将永远不会被执行。这完全取决于JVM GC。
即使GC可能运行,它也可能无法收集给定的对象。只要仍未收集未被引用的Object,就永远不会调用其 finalize()

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.

此外,在程序终止之前,可能根本不会调用垃圾收集。在这种情况下,内存作为一个整体返回到操作系统,没有任何GC。并且没有任何最终确定方法调用。

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.

你的第二个答案是对的。如果对象仍在使用中,无论GC是否运行,都无法收集(并且 finalize()被调用),除非您使用 WeakReference 或类似的东西。

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.

这篇关于什么时候执行finalize()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 17:51