Search code examples
javamultithreadingshutdown

setting the shut down hook as non daemon


when my java app closes - my shut down hook doesnt run fully till the end.
in the java doc it mentions that

Shutdown hooks should also finish their work quickly...

(refer to the doc) as it closes the app quick.
I want to try and solve it (maybe set it to non daemon thread)

So I tried first to reconstruct it using a simple app.
I add the hook using

    Runtime.getRuntime().addShutdownHook(new Thread(){
        @Override public void run() {
            for (int i = 0; i < 1000000; i++) {
                System.out.println(i);
            }

        }
    });

and I throw a

            System.exit(1);

in this example the shutdown process counts until the end with no problem. (So no reconstraction)

How can I fix it in my app?
How can I reconstruct it ?


Solution

  • The javadoc is giving a recommendation. If the JVM is going down, your hooks should not be running for minutes doing various things. They are designed to cleanup after the program.

    The hook threads are started and then join() is called on them so the JVM always waits for them to complete before stopping. Here's the code from ApplicationShutdownHooks.runHooks():

    static void runHooks() {
        ...
        for (Thread hook : threads) {
            hook.start();
        }
        for (Thread hook : threads) {
            hook.join();
        }
    }
    

    This said, if you call System.exit(1);, the JVM will exit immediately.