1

I have a product service in Java. In our code I am creating shut down hook, but when I stop service it is not calling shut down hook consistently. Out of 5 stop calls it has called shutdown hook only once.

Runnable shutdownHandler = new Runnable() {

    @Override
    public void run() {

        s_log.info("Shutting down thread..");
    }

};

Runtime.getRuntime().addShutdownHook(
        new Thread(shutdownHandler, "shutdownthread"));

Can anybody please tell me what could be the reason behind this not getting called consistently?

8
  • How is the process being shutdown? Depending on how it is killed, it might not get a chance to run the shutdown hook. You should never assume it will be run as the process could be killed in such a way it can't be run. Commented Mar 9, 2016 at 20:31
  • Its a standard java process registered in windows. I am stopping service from service console of windows Commented Mar 9, 2016 at 20:34
  • What service runner are you using? Java doesn't have a built-in runner. Commented Mar 9, 2016 at 20:42
  • 1
    Maybe the logging service shuts down faster? Commented Mar 9, 2016 at 20:43
  • 2
    Do you have a proof that the hook doesn't run in those cases? Logging a message is not a proof since some logging frameworks (e.g. Log4j2) have their own shutdown hooks and thus may be already shut down when you attempt to use the logging method. Commented Mar 9, 2016 at 20:43

2 Answers 2

1

Check the following code:

Runnable shutdownHandler = new Runnable() {
    @Override
    public void run() {
        System.out.println("Shutting down thread..");
    }
};

Runtime.getRuntime().addShutdownHook(
        new Thread(shutdownHandler, "shutdownthread"));

and if it gives you expected output, you need to check the documentation of your logging framework.

Sign up to request clarification or add additional context in comments.

Comments

0

I am also finding that my framework (Jooby) and Java shutdown hooks work fine on my Mac on IntelliJ which sends a kill SIGINT (-2) however on Ubuntu Server 20.04 LTS they don't run.

As my Java app is a webapp I came up with a simple workaround:

  1. Setup a controller to listen to some url that isn't easily guessable e.g.

    /exit/fuuzfhuaBFDUWYEGLI823y82941u9y47t3u45
    
  2. Have the controller simply do the following:

    System.exit(0)
    

Do a curl or wget from a script to the URL and the shutdown hooks all fire as JVM comes down.

I suspect for some reason on Linux there is a bug and no matter what interrupt that I use besides SIGKILL they all effectively behave like SIGKILL and the JVM comes down hard/abruptly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.