3

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.

tuk
  • 5,941
  • 14
  • 79
  • 162
  • 1
    There's no logical difference... In java not marking a thread daemon says that that thread needs to exit before the shutdown sequence begins. Shutdown hooks are executed at the start of the shutdown sequence. Because the shutdown sequence has already begun when shutdown hooks are run, them being flagged daemon or not is doesn't make a difference, they run to completion either way. – John Stringer Nov 21 '19 at 11:01

1 Answers1

2

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) {
            }
        }
    }
apangin
  • 92,924
  • 10
  • 193
  • 247