简体   繁体   中英

Difference in adding a daemon vs non-daemon thread in a java shutdown hook

I have seen this discussion in stackoverflow . But it is not clear to me if marking a thread as daemon in ShutdownHook is same as marking it as non-daemon?

Thread t = new Thread(this::someMethod, "shutdown_hook");
t.setDaemon(true);
Runtime.getRuntime().addShutdownHook(t);

Will the behavior be same if I don't do t.setDaemon(true); in the above code.

I am using java 8.

There is no difference, whether a shutdown hook Thread is daemon or not.

As the specification for Runtime.addShutdownHook says,

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 shutdown was initiated by invoking the exit method.

and

Once the shutdown sequence has begun it can be stopped only by invoking the halt method

JDK implementation follows these rules. As we see in the source code , runHooks starts hook threads and waits until all of them finish:

    for (Thread hook : threads) {
        hook.start();
    }
    for (Thread hook : threads) {
        while (true) {
            try {
                hook.join();
                break;
            } catch (InterruptedException ignored) {
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM