问题描述
我需要知道 finalize()
方法在 JVM
中被调用.我创建了一个测试类,该类在通过覆盖调用 finalize()
方法时写入文件.它不被执行.谁能告诉我它没有执行的原因吗?
I need to know when the finalize()
method is called in the JVM
. I created a test class which writes into a file when the finalize()
method is called by overriding it. It is not executed. Can anybody tell me the reason why it is not executing?
推荐答案
一般来说最好不要依赖finalize()
来做任何清理等操作
In general it's best not to rely on finalize()
to do any cleaning up etc.
根据 Javadoc(值得一读),它是:
According to the Javadoc (which it would be worth reading), it is:
当垃圾收集器确定不再有对该对象的引用时,由垃圾收集器对该对象调用.
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
正如 Joachim 所指出的,如果对象总是可访问的,这可能永远不会在程序的生命周期中发生.
As Joachim pointed out, this may never happen in the life of a program if the object is always accessible.
此外,垃圾收集器不能保证在任何特定时间运行.一般来说,我想说的是 finalize()
可能不是一般使用的最佳方法,除非有特定的需要.
Also, the garbage collector is not guaranteed to run at any specific time. In general, what I'm trying to say is finalize()
is probably not the best method to use in general unless there's something specific you need it for.
这篇关于Java 什么时候调用 finalize() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!