How to gracefuly shutdown a Spring Boot application by start-stop-daemon [duplicate]
Asked Answered
L

2

14

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?

Least answered 18/4, 2016 at 10:27 Comment(2)
If you're interested in shutting down the embedded servlet container gracefully, please see this Spring Boot issue.Zandrazandt
Does this answer your question? Does spring have a shutdown process to put cleanup code?Apul
B
22

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

Bowse answered 18/4, 2016 at 10:59 Comment(3)
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.Least
@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.Bowse
It should be noted, though, that the use of DisposableBean is not recommended by Spring, '... because it unnecessarily couples the code to Spring.' [docs.spring.io/spring/docs/current/spring-framework-reference/… Better use @PreDestroy instead.Phloem
P
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###");
  }
}
Phillida answered 19/11, 2018 at 7:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.