Java 有析构函数吗? [英] Is there a destructor for Java?

查看:38
本文介绍了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 有析构函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆