DEV Community

Alex Yaroslavsky
Alex Yaroslavsky

Posted on

2 1

Spring Boot and Graceful Service Shutdown

Imagine your service running in Kubernetes, having the time of its life, and then suddenly you push a new version through the pipeline. Before starting the new version, Kubernetes needs to stop the old one. It first asks your service nicely to exit (SIGTERM), if your service doesn't respond to that it will be violently killed (SIGKILL) after several seconds. So if you want to close various resources correctly and exit gracefully, there are some steps you must take.

Below is an example of a generic skeleton for a Spring Boot Service that wants to handle shutdowns gracefully.

The main idea:

  • Start a separate thread with main application logic
  • Wait for application closing event (called upon SIGTERM)
  • Interrupt the main application logic thread and exit
  • PROFIT;

P.S. Don't forget to eat destroy your Beans, for Beans that implement the AutoClosable interface this is extremely simple:
@Bean(destroyMethod = "close")

@Slf4j
@SpringBootApplication
public class Application implements ApplicationRunner, Runnable, ExitCodeGenerator {
private final SomeAppLogic someAppLogic;
private final Thread mainThread;
private int exitCode = 0;
public static void main(String[] args) {
System.exit(SpringApplication.exit(SpringApplication.run(Application.class, args)));
}
@Autowired
Application(SomeAppLogic someAppLogic) {
this.someAppLogic = someAppLogic;
mainThread = new Thread(this, "mainThread");
}
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
log.info("Starting...");
mainThread.start();
mainThread.join();
log.info("Exiting...");
}
@EventListener
public void onApplicationEvent(ContextClosedEvent event) {
mainThread.interrupt();
}
@Override
public void run() {
try {
someAppLogic.doLogic();
} catch (Exception e) {
if (e instanceof InterruptedException || e.getCause() instanceof InterruptedException) {
log.info("Interrupted...");
} else {
log.error("Exception occurred", e);
exitCode = 1;
}
}
}
@Override
public int getExitCode() {
return exitCode;
}
}

Top comments (0)

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️