Java有析构函数吗?我好像找不到任何关于这个的文件。如果没有,我怎样才能达到同样的效果?

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

作为一个通常的C/ c++程序员,我认为这是微不足道的实现。(因此我打算最后实现它。)我构造了我的程序,使所有“可重置”的对象都在同一个类中,这样当按下重置按钮时,我就可以销毁所有“活动”对象。

我在想,如果我所做的只是解除对数据的引用,并等待垃圾收集器收集它们,如果我的用户重复输入数据并按下重置按钮,是否会出现内存泄漏?我还在想,既然Java作为一种语言相当成熟,应该有一种方法来防止这种情况发生或优雅地解决这个问题。


当前回答

想想最初的问题……我认为我们可以从所有其他学习过的答案中得出结论,也可以从Bloch的《有效Java》中得出结论,第7项“避免终结器”,以一种不适合Java语言的方式寻求合理问题的解决方案……

... OP实际上想要的是将所有需要重置的对象保存在一种“playpen”中,而所有其他不可重置的对象只能通过某种访问器对象引用该对象,这难道不是一个非常明显的解决方案吗?

然后当你需要“重置”时,你断开现有的游戏笔并创建一个新的游戏笔:游戏笔中所有的对象都被抛到一边,永远不会返回,有一天会被GC收集。

如果这些对象中的任何一个是可关闭的(或者不是,但有一个关闭方法),你可以在它们被创建(可能打开)时将它们放在游戏笔的一个袋子中,访问器在切断游戏笔之前的最后一个动作将是通过所有的关闭对象关闭它们……?

代码可能看起来像这样:

accessor.getPlaypen().closeCloseables();
accessor.setPlaypen( new Playpen() );

closeCloseables可能是一个阻塞方法,可能涉及一个闩锁(例如CountdownLatch),以处理(并等待)任何特定于Playpen的线程中的任何可运行对象/可调用对象在适当的时候结束,特别是在JavaFX线程中。

其他回答

不,. lang。Object#finalize是最接近的。

但是,不保证何时(以及是否)调用它。 看到:java.lang.Runtime # runFinalizersOnExit(布尔)

我同意大部分答案。

你不应该完全依赖finalize或ShutdownHook

完成

The JVM does not guarantee when this finalize() method will be invoked. finalize() gets called only once by GC thread. If an object revives itself from finalizing method, then finalize will not be called again. In your application, you may have some live objects, on which garbage collection is never invoked. Any Exception that is thrown by the finalizing method is ignored by the GC thread System.runFinalization(true) and Runtime.getRuntime().runFinalization(true) methods increase the probability of invoking finalize() method but now these two methods have been deprecated. These methods are very dangerous due to lack of thread safety and possible deadlock creation.

shutdownHooks

public void addShutdownHook(Thread hook)

注册一个新的虚拟机关闭钩子。

Java虚拟机在响应两种事件时关闭:

The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown. A shutdown hook is simply an initialized but non-started thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if the shutdown was initiated by invoking the exit method. Shutdown hooks should also finish their work quickly. When a program invokes exit the expectation is that the virtual machine will promptly shut down and exit. But even Oracle documentation quoted that

在极少数情况下,虚拟机可能会中止,即停止运行而不完全关闭

这发生在虚拟机从外部终止时,例如在Unix上使用SIGKILL信号或在Microsoft Windows上使用TerminateProcess调用。如果本机方法出错,虚拟机也可能中止,例如破坏内部数据结构或试图访问不存在的内存。如果虚拟机中止,则不能保证是否会运行任何shutdown钩子。

结论:合理使用try{} catch{} finally{}块,释放finally(}块中的关键资源。在finally{}块中释放资源时,捕获Exception和Throwable。

我刚刚扫描的所有答案的缺失形式是终结器更安全的替代品。关于使用try-with-resources和避免终结器,所有其他答案都是正确的,因为它们不可靠,现在已弃用……

但是他们没有提到清洁工。Java 9中添加了清洁器,以一种比终结器更好的方式显式地处理清理工作。

https://docs.oracle.com/javase/9/docs/api/java/lang/ref/Cleaner.html

在Java中,最接近析构函数的是finalize()方法。与传统析构函数的最大区别在于,您不能确定何时调用它,因为这是垃圾收集器的职责。我强烈建议在使用它之前仔细阅读它,因为用于文件句柄等的典型RAIA模式不能可靠地使用finalize()。

如果你只是担心记忆,那就别担心了。相信GC,它做得不错。实际上,我发现它非常高效,在某些情况下,创建一堆小对象比使用大数组的性能更好。