When is the finalize() method called in Java?(Java 什么时候调用 finalize() 方法?)
问题描述
我需要知道 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() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 什么时候调用 finalize() 方法?
基础教程推荐
- 大摇大摆的枚举 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
