Is there a destructor for Java?(Java有析构函数吗?)
问题描述
Java 有析构函数吗?我似乎无法找到任何有关此的文档.如果没有,我怎样才能达到同样的效果?
Is there a destructor for Java? I don't seem to be able to find any documentation on this. If there isn't, how can I achieve the same effect?
为了使我的问题更具体,我正在编写一个处理数据的应用程序,并且规范说应该有一个重置"按钮,可以将应用程序恢复到其刚启动的原始状态.但是,除非应用程序关闭或按下重置按钮,否则所有数据都必须是实时的".
To make my question more specific, I am writing an application that deals with data and the specification say that there should be a 'reset' button that brings the application back to its original just launched state. However, all data have to be 'live' unless the application is closed or reset button is pressed.
我通常是一名 C/C++ 程序员,我认为这很容易实现.(因此我计划最后实现它.)我构建了我的程序,使所有可重置"对象都在同一个类中,这样我就可以在按下重置按钮时销毁所有活动"对象.
Being usually a C/C++ programmer, I thought this would be trivial to implement. (And hence I planned to implement it last.) I structured my program such that all the 'reset-able' objects would be in the same class so that I can just destroy all 'live' objects when a reset button is pressed.
我在想如果我所做的只是取消引用数据并等待垃圾收集器收集它们,如果我的用户重复输入数据并按下重置按钮,会不会出现内存泄漏?我也在想,既然 Java 作为一门语言已经相当成熟,应该有一种方法可以防止这种情况发生或优雅地解决这个问题.
I was thinking if all I did was just to dereference the data and wait for the garbage collector to collect them, wouldn't there be a memory leak if my user repeatedly entered data and pressed the reset button? I was also thinking since Java is quite mature as a language, there should be a way to prevent this from happening or gracefully tackle this.
推荐答案
因为 Java 是一种垃圾收集语言,所以您无法预测对象何时(或什至)会被销毁.因此没有直接等效的析构函数.
Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor.
有一个名为finalize
的继承方法,但这完全由垃圾收集器决定调用.所以对于需要明确整理的类,约定是定义一个 close 方法并使用 finalize 仅用于完整性检查(即如果 close 没有被调用,现在就做并记录错误).
There is an inherited method called finalize
, but this is called entirely at the discretion of the garbage collector. So for classes that need to explicitly tidy up, the convention is to define a close method and use finalize only for sanity checking (i.e. if close has not been called do it now and log an error).
最近有一个引发对finalize的深入讨论的问题,所以如果需要的话应该提供更多的深度......
There was a question that spawned in-depth discussion of finalize recently, so that should provide more depth if required...
这篇关于Java有析构函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java有析构函数吗?
基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01