Search code examples
javaspring-bootapache-camelwindows-servicesshutdown-hook

Springboot shutdown hook not working with Windows TaskKill


I have an Apache Camel Spring Boot Java 8 app that runs on Windows 10. It shuts down gracefully when CTRL-C is pressed, although sometimes I have to press it twice. But when using TaskKill, the answer always is

C:\Windows\system32>taskkill /PID 1048
ERROR: The process with PID 1048 could not be terminated.
Reason: This process can only be terminated forcefully (with /F option).

My goal is to create a Windows service, but again, when stopping the service, the app is killed abruptly. Why CTRL-C is working, and TaskKill not? What can I do to have a Windows service that shuts down gracefully? The main class of my app looks like

import org.apache.camel.spring.Main;

@SpringBootApplication
@EnableScheduling
public class InformerApplication {

  public static void main(String[] args) throws Exception {
    SpringApplication.run(InformerApplication.class, new String[0]);
    Main.main( args);
  }
}

Solution

  • From Java Shutdown Hooks API

    The Java virtual machine shuts down in response to two kinds of events:

    • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked
    • The virtual machine is terminated in response to a user interrupt, such as typing CTRL+C (SIGINT), or a system-wide event, such as user logoff or system shutdown.

    https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)

    WM_CLOSE Signal from KillTask is not handled.