是否有Java的析构函数? [英] Is there a destructor for Java?

查看:200
本文介绍了是否有Java的析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有Java的析构函数?我似乎无法找到任何关于此的文档。如果没有,我怎么能达到同样的效果?



为了使我的问题更具体,我正在编写一个处理数据的应用程序,规范说应该有一个重置按钮,使应用程序恢复到其原始的刚启动状态。但是,除非关闭应用程序或按下重置按钮,否则所有数据都必须是实时。



通常是C / C ++程序员,我认为这将是微不足道的实施。 (因此我计划最后实现它。)我构建了我的程序,以便所有'可重置'对象都在同一个类中,这样当按下重置按钮时我就可以销毁所有'实时'对象。 / p>

我在想,如果我所做的只是取消引用数据并等待垃圾收集器收集它们,如果我的用户反复输入就不会有内存泄漏数据并按下重置按钮?我也在想,因为Java作为一种语言非常成熟,应该有办法防止这种情况发生或优雅地解决这个问题。

解决方案

因为Java是一种垃圾收集语言,所以无法预测何时(或者甚至是)对象将被销毁。因此,没有直接等价的析构函数。



有一个名为 finalize 的继承方法,但这被称为完全由垃圾收集者自行决定。因此,对于需要明确整理的类,惯例是定义 close 方法并仅使用finalize进行健全性检查(即,如果 close 尚未被调用,请立即执行此操作并记录错误。)



产生深入讨论最终确定的问题,以便在需要时提供更多深度...


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.

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.

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.

解决方案

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.

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).

There was a question that spawned in-depth discussion of finalize recently, so that should provide more depth if required...

这篇关于是否有Java的析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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