Search code examples
javashutdown-hook

Collection not being iterated in a java shutdown hook


I have been struggling for a few hours already on that nonsensical problem, so now I'm seeking for help.

1 liner: my shutdown hook is apparently terminated before it finishes its duty.

The code I'm running looks like this:

class Test {

    static {
        Runtime.getRuntime().addShutdownHook(new Thread(Test::shutdown));
    }

    // more methods
    private static void shutdown() {
        Collection<Foo> coll = some.instance.ofHashMap.values();
        System.out.println("collSize=" + coll.size());
        for (Foo o : coll) {
            System.out.println("Calling bar on foo");
            o.bar();
        }
        System.out.println("End of hook");
    }
}

But the output is:

collSize=1

If I run the jvm with the -server option, I might get lucky and the "Calling bar on foo" print but it still doesn't print "End of hook".

Unfortunately, I haven't been able to create a short executable example that shows the problem. I have one but it shows everything's working fine and the collection is iterated as expected. The code above is an extract of a much bigger program i'm working on, but my shut down is hook is doing nothing more than the above (get a non empty collection and iterate).

Any ideas of what might be happening? I am totally lost here...

Notes: - Code is written, compiled and run for/with Java 8u45 - I kill the program with Ctrl+C, as a result, the JVM exists with code 130


Solution

  • Turns out:

    • it was mainly a IO problem: unlike in the example above, i use a logger from log4j2 to print the info. log4j2 has its own shutdownHook which kills all the loggers faster than my shutdown hook since shutdown hooks are executed in parallel in the JVM. After disabling log4j2 shutdownHook, everything appeared to work as expected.
    • the hook was always executed fully (easily proven by attaching a debugger to the jvm)
    • in my particular case, i forgot to shutdown+await on my thread pools to do all the clean up i wanted to
    • i should have slept on it before posting here :/

    Thank you all for the quick replies and help.