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有析构函数吗?
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01