shutdown hook vs finalizer方法
我只是不明白为什么必须使用Runtime.addShutdownHook。如果你想在jvm退出时做一些清理,为什么不重载守护进程类的finalize方法。使用shutdown hook而不是finalize方法有什么好处。
I just fail to understand why must one use Runtime.addShutdownHook. If you want to do some cleanup when the jvm exits, why not just overload the finalize method of the daemon class. What is the advantage of using shutdown hook over finalize method.
还有一个不推荐使用的函数runFinalizersOnExit。如果我将其设置为false,我相信终结器将无法运行。这与java保证终结器总是在垃圾收集之前运行相矛盾。
Also there is a deprecated function runFinalizersOnExit. If I set it to false, I believe finalizers won't run. This contradicts the java guarantee that finalizers always run before garbage collections.
无法保证终结器永远不会运行。当对象被垃圾收集时,将调用 finalize()
。但是当程序运行时,垃圾收集器可能不会收集任何东西。
There is no guarantee that a finalizer will ever run. finalize()
is called when the object is garbage collected. But the garbage collector may not collect anything when the program runs.
相反,当jvm正常退出时,会运行关闭挂钩。所以,即使这不是100%保证,但它非常接近。只有少数边缘情况不会运行关闭钩子。
Shutdown hooks by contrast are run when the jvm exits normally. so even that isn't 100% guarantee either but it's pretty close. There are only a few edge cases where a shutdown hook doesn't run.
编辑
我抬头看边缘情况没有执行关闭钩子
EDIT I looked up the edge cases where a shutdown hook is not executed
执行关闭钩子 IS :
- 当所有JVM线程都已完成执行时
- 因为调用System.exit()
- 因为用户点击了CNTRL-C
- 系统级别关闭或用户注销
- When all of JVM threads have completed execution
- Because of call to System.exit()
- Because user hit CNTRL-C
- System level shutdown or User Log-Off
关闭挂钩不是已执行:
- 如果VM由于本机代码中的错误而崩溃,则无法保证挂钩是否存在错误将运行。
- 如果在Linux上使用-kill命令或在Windows上使用Terminate Process终止JVM,则JVM立即退出