How does the JVM terminate daemon threads? or How to write daemon threads that terminate gracefully(JVM 如何终止守护线程?或如何编写优雅终止的守护线程)
问题描述
假设场景:
我有一个守护线程负责一些 I/O,主线程完成并返回,JVM 决定终止我的守护线程.
Hypothetical scenario:
I have a daemon thread responsible for some I/O, the main thread finishes and returns, and the JVM decides to terminate my daemon thread.
它是如何做到的?打断?敲定?如何编码我的守护线程,以便它在终止时做出优雅的反应?
How does it do so? Interrupt? Finalize? How can I code my daemon thread so that it reacts gracefully when terminated?
推荐答案
我只是写了以下代码作为测试:
I just wrote the following code as a test:
public class DaemonThreadPlay {
public static void main(String [] args) {
Thread daemonThread = new Thread() {
public void run() {
while (true) {
try {
System.out.println("Try block executed");
Thread.sleep(1000l);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
@Override
public void finalize() {
System.out.println("Finalize method called");
}
};
daemonThread.setDaemon(true);
daemonThread.start();
try {
Thread.sleep(2500l);
} catch (Throwable t) {
//NO-OP
}
}
}
我在守护线程的 catch 块和 finalize 方法中设置了断点.即使执行了 try 块,也没有到达断点.显然这段代码存在同步/计时问题,但我认为我们可以安全地得出结论,守护线程不会在关闭时中断,也不一定会调用它们的 finalize() 方法.
I put breakpoints in the catch block of the daemon thread and in the finalize method. Neither breakpoint was reached even though the try block was executed. Obviously this code has synchronization/timing issues, but I think we can safely conclude that daemon threads are not interrupted on shutdown nor are their finalize() methods necessarily invoked.
您始终可以向 JVM 运行时添加关闭挂钩:
You can always add a shutdown hook to the JVM Runtime:
Thread shutdownHook = ... // construct thread that somehow
// knows about all the daemon threads
Runtime.getRuntime().addShutdownHook(shutdownHook);
您的关闭挂钩显然可以执行优雅"关闭所需的任何任务.
Your shutdown hook can obviously do whatever tasks are required for a "graceful" shutdown.
这篇关于JVM 如何终止守护线程?或如何编写优雅终止的守护线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JVM 如何终止守护线程?或如何编写优雅终止的守护线程
基础教程推荐
- 大摇大摆的枚举 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 从 python 访问 JVM 2022-01-01
