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;
}
}

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay