12

We have a multithreaded Spring Boot Application, which runs on Linux machine as a daemon. When I try to stop the application by start-stop-daemon like this

start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME

The SIGTERM signal is sent and application immetiately ends. However I want the application to wait, until every thread finishes it's work.

Is there any way, how to manage what happens, when SIGTERM signal is received?

Michal Krasny
  • 5,434
  • 7
  • 36
  • 64
  • If you're interested in shutting down the embedded servlet container gracefully, please see [this Spring Boot issue](https://github.com/spring-projects/spring-boot/issues/4657). – Andy Wilkinson Apr 18 '16 at 11:44
  • 1
    Does this answer your question? [Does spring have a shutdown process to put cleanup code?](https://stackoverflow.com/questions/8585350/does-spring-have-a-shutdown-process-to-put-cleanup-code) – Jason Law Oct 14 '20 at 06:41

2 Answers2

20

Spring Boot app registers a shutdown hook with the JVM to ensure that the ApplicationContext is closed gracefully on exit. Create bean (or beans) that implements DisposableBean or has method with @PreDestroy annotation. This bean will be invoked on app shutdown.

http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-application-exit

Evgeny
  • 2,483
  • 1
  • 17
  • 24
  • 1
    Thank you for the tip. However this does not solve my problem, because I somehow need to intercept the SIGTERM signal and wait until application finishes it's work. This allows me to do some cleanup, but if I understand it correctly, this does not allow me to prevent termination of currently running method. – Michal Krasny Apr 19 '16 at 13:02
  • @Michal You're right, it doesn't allow you to prevent termination. But it allows to implement threads stopping logic and wait until threads finish. The JVM won't be terminated if shutdown hook works. – Evgeny Apr 19 '16 at 13:26
  • 1
    It should be noted, though, that the use of `DisposableBean` is not recommended by Spring, '... because it unnecessarily couples the code to Spring.' [https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factory-lifecycle-disposablebean] Better use `@PreDestroy` instead. – Stefan Dec 07 '17 at 07:44
5

sample as mentioned by @Evgeny

@SpringBootApplication
@Slf4j
public class SpringBootShutdownHookApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringBootShutdownHookApplication.class, args);
  }

  @PreDestroy
  public void onExit() {
    log.info("###STOPing###");
    try {
      Thread.sleep(5 * 1000);
    } catch (InterruptedException e) {
      log.error("", e);;
    }
    log.info("###STOP FROM THE LIFECYCLE###");
  }
}
lizhipeng
  • 661
  • 7
  • 6