JVM如何终止守护程序线程?或者如何编写优雅终止的守护程序线程 [英] How does the JVM terminate daemon threads? or How to write daemon threads that terminate gracefully

查看:132
本文介绍了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如何终止守护程序线程?或者如何编写优雅终止的守护程序线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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