Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jvm

java-8

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.

like image 248
tuk Avatar asked Oct 21 '25 12:10

tuk


1 Answers

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) {
            }
        }
    }
like image 140
apangin Avatar answered Oct 23 '25 03:10

apangin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!