I have added ShutDownHook to my Spring Boot Application. When I pass SIGTERM to my application, shutdown hook got triggered but it is terminated in halfway i.e, in middle of execution. Googled it and tried many solutions it is not working. Some expert, please help me on this.
Main Class:
ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(MyApp.class)
.profiles("default")
.registerShutdownHook(false)
.build()
.run(args);
Runtime.getRuntime().addShutdownHook(new Thread(new GracefulShutdownHook(applicationContext)));
GracefulShutdownHook Class:
public class GracefulShutdownHook implements Runnable {
private final ConfigurableApplicationContext applicationContext;
public GracefulShutdownHook(ConfigurableApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public void run() {
try {
log.info("Gonna wait for 5 seconds before shutdown SpringContext!");
Thread.sleep(5 * 1000);
log.info("Spring Application context starting to shutdown");
applicationContext.close();
log.info("Spring Application context is shutdown");
} catch (InterruptedException e) {
log.error("Error while gracefulshutdown Thread.sleep", e);
}
}
}
I want shutdown hook to update some cache and also some logic which consumes some extra processing time.
Log when I try to kill using 'kill -15':
Apr 13 10:08:22 ssed java[14354]: 2018-04-13T10:08:22,778 INFO [c.o.GracefulShutdownHook] -- Gonna wait for 10 seconds before shutdown SpringContext!
I am using embedded Jetty server. I have also enabled Jetty log but only above log getting printed while shutdown. My expectation is applicationContext.close() should be called after 10 sec sleep but thread is not resuming after 10 sec.
Please find the below log when I try to stop using systemctl.
Apr 12 15:24:51 vm33 systemd[1]: Stopping Session Application Service...
Apr 12 15:24:51 vm33 java[29538]: 2018-04-12T15:24:51,421 INFO [c.o.GracefulShutdownHook] -- Gonna wait for 10 seconds before shutdown SpringContext!
Apr 12 15:25:01 vm33 systemd[1]: Stopped Session Application Service.
I developed one simple basic java program with shutdown hook and try to interrupt using 'kill -15'. The shutdown hook is working fine perfectly.