问题:
Is there a destructor for Java? 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. 我通常是C / C ++程序员,所以我认为这是微不足道的。 (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. 我也在想,因为Java作为一种语言已经相当成熟,所以应该有一种方法可以防止这种情况的发生或妥善解决。
解决方案:
参考一: https://stackoom.com/question/ijQ/Java是否有析构函数
参考二: https://oldbug.net/q/ijQ/Is-there-a-destructor-for-Java