1

I am trying to add a shutdown hook via Runtime.getRuntime().addShutdownHook() in a Spring Gradle application.

I tried adding an anonymous thread subclass to the Application.java class from this exact tutorial So that it looks like this:

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
            Thread thread = new Thread() {
                    public void run() {
                            System.out.println("Shutdown Thread!");
                    }
            };
            Runtime.getRuntime().addShutdownHook(thread);
            SpringApplication.run(Application.class, args);
    }
}

However, I am not seeing the desired behavior: printing "Shutdown Thread!" on exiting the application. What is going wrong here?

edit: I have been shutting it down using control + c on the terminal where it is running. I am running it on the OSX terminal

efong5
  • 366
  • 1
  • 6
  • 21
  • related: https://stackoverflow.com/questions/26678208/spring-boot-shutdown-hook –  Nov 25 '17 at 14:36
  • 1
    How do you exit the application? – helospark Nov 25 '17 at 15:18
  • I just control c it in the terminal. I'll add that in. Do I need a more graceful shutdown to do this? – efong5 Nov 25 '17 at 23:34
  • 1
    @efong5 Ctrl+C should call the shutdown hooks. Checked your code on Linux, the message is printed, so I cannot reproduce the issue. Are you absolutely sure, it is not printed? Maybe there are some buffering problem, try flushing the output explicitly using `System.out.flush()`. Maybe your console sends a JVM force kill signal (kill -9) on ctrl+c, it worth a try to shutdown JVM more gracefully eg. `SpringApplication.exit`, or `System.exit()` – helospark Nov 26 '17 at 11:13
  • @helospark Thanks, seems like the graceful exit was the issue. I'll add details about my environment into my question, if you submit your comment as an answer I'll mark it as answered. – efong5 Nov 27 '17 at 22:46

0 Answers0