Backend Development 7 min read

Graceful Shutdown Techniques for Spring Boot Applications

The article explains why killing a Spring Boot process with SIGKILL is unsafe and presents five practical ways—using Actuator, closing the application context, writing a PID file, invoking SpringApplication.exit, and creating a custom shutdown controller—to achieve a graceful shutdown while ensuring @PreDestroy methods run and resources are released.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Graceful Shutdown Techniques for Spring Boot Applications

When stopping a Spring Boot service, using kill -9 terminates the JVM abruptly, bypassing any cleanup logic; a graceful shutdown is required to let unfinished tasks finish, log information, and notify dependent systems.

Method 1 – Actuator shutdown endpoint : Add the Actuator starter dependency and enable the shutdown endpoint in application.properties (e.g., management.endpoint.shutdown.enabled=true and expose it via management.endpoints.web.exposure.include=shutdown ). Define a bean with a @PreDestroy method to log a message, then trigger shutdown with curl -X POST http://localhost:3333/actuator/shutdown .

Method 2 – Close the application context : Obtain the ConfigurableApplicationContext from SpringApplication.run(...) , wait (e.g., 10 seconds), and call ctx.close() . The @PreDestroy method will be executed automatically.

Method 3 – PID file writer : Configure ApplicationPidFileWriter with a custom path (e.g., "/Users/huangqingshi/app.pid" ) when building the SpringApplication . The PID can then be stopped with cat /Users/huangqingshi/app.pid | xargs kill , which also invokes @PreDestroy callbacks.

Method 4 – SpringApplication.exit : After the application starts, call a helper method that executes int exitCode = SpringApplication.exit(context, () -> 0); System.exit(exitCode); . This runs all shutdown hooks and returns an exit code to the JVM.

Method 5 – Custom shutdown controller : Implement a @RestController that implements ApplicationContextAware . Expose a POST /shutDownContext endpoint that casts the stored ApplicationContext to ConfigurableApplicationContext and calls close() , returning a confirmation string.

All five approaches achieve graceful termination, but in production you must protect the shutdown endpoints (e.g., restrict to internal networks or add authentication) to avoid accidental or malicious service interruption.

backendJavaSpring BootGraceful ShutdownActuatorPreDestroy
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.