Spring Boot
application shutdown
programmatic shutdown
Java
Spring Framework

Programmatically shut down Spring Boot application

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Spring Boot is a powerful framework for building Java-based applications, providing a variety of services and configurations that streamline the development process. One common requirement in enterprise applications is the need to programmatically shut down the application. This necessity can arise due to maintenance, error handling, resource cleanup, or infrastructure constraints. In this article, we explore different methods to achieve controlled shutdowns within a Spring Boot application.

Various Methods for Programmatic Shutdown

Spring Boot offers multiple ways to programmatically shut down an application:

1. Using SpringApplication.exit

The SpringApplication.exit method provides a straightforward mechanism to shut down a Spring Boot application programmatically. This method leverages the ExitCodeGenerator interface, allowing for customized exit codes upon termination.

Example:

java
1import org.springframework.boot.SpringApplication;
2import org.springframework.boot.autoconfigure.SpringBootApplication;
3
4@SpringBootApplication
5public class MyApp {
6
7    public static void main(String[] args) {
8        SpringApplication app = new SpringApplication(MyApp.class);
9        int exitCode = SpringApplication.exit(app.run(args), () -> 0);
10        System.exit(exitCode);
11    }
12}

In this example, we use the SpringApplication.exit() method, passing an implementation of ExitCodeGenerator with a custom exit code. The System.exit() call is utilized to terminate the application.

2. Registering a Shutdown Hook

Java provides the ability to register a shutdown hook to JVM. This way, you can gracefully shut down the Spring Boot application by invoking custom logic upon application termination.

Example:

java
1import org.springframework.context.ConfigurableApplicationContext;
2import org.springframework.boot.SpringApplication;
3import org.springframework.boot.autoconfigure.SpringBootApplication;
4
5@SpringBootApplication
6public class MyAppWithHook {
7
8    public static void main(String[] args) {
9        ConfigurableApplicationContext context = SpringApplication.run(MyAppWithHook.class, args);
10        
11        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
12            // Custom cleanup code
13            System.out.println("Shutdown Hook triggered.");
14            context.close();
15        }));
16    }
17}

This approach adds a shutdown hook, ensuring that context.close() is called, which nicely shuts down the application context.

3. Using Spring Boot Actuator

Spring Boot Actuator offers an endpoint that allows programmatic shutdown if enabled. The /shutdown endpoint exposes functionality to close the application context.

Example:

Configuration to enable shutdown endpoint in application.properties:

properties
management.endpoint.shutdown.enabled=true
management.endpoints.web.exposure.include=shutdown

With these properties set, sending an HTTP POST request to /actuator/shutdown will initiate the shutdown process:

bash
curl -X POST http://localhost:8080/actuator/shutdown

Security Consideration: Exposing the /shutdown endpoint poses security risks. It should be adequately protected using security mechanisms such as authentication and limited network exposure.

4. Trigger a Shutdown from Application Events

Spring Boot’s eventing and callback mechanism allow listening to application context events. You can listen for specific events and trigger a shutdown under predefined conditions.

Example using ApplicationListener:

java
1import org.springframework.context.ApplicationListener;
2import org.springframework.context.event.ContextRefreshedEvent;
3import org.springframework.stereotype.Component;
4
5@Component
6public class AppStartupShutdown implements ApplicationListener<ContextRefreshedEvent> {
7    
8    @Override
9    public void onApplicationEvent(ContextRefreshedEvent event) {
10        System.out.println("Application started. Trigger shutdown logic here.");
11
12        // Logic to trigger shutdown
13        if (shouldShutdown()) {
14            SpringApplication.exit(event.getApplicationContext(), () -> 0);
15        }
16    }
17
18    private boolean shouldShutdown() {
19        // Replace logic as needed to determine if shutdown is appropriate
20        return false;
21    }
22}

In this example, AppStartupShutdown listens for a ContextRefreshedEvent, executing shutdown logic if a custom condition is met.

Summary of Shutdown Methods

MethodDescriptionUse Case
SpringApplication.exitProvides direct method to terminate the app with a custom exit code.Straightforward programmatic exit.
Shutdown HookAdds a JVM-level shutdown procedure for cleanup.Resource deallocation during JVM termination.
Spring Boot ActuatorExposes /shutdown endpoint to trigger shutdowns over HTTP.Remote shutdown capabilities via HTTP. Requires security considerations.
Application EventsLeverages Spring's application context events for conditional shutdowns.Useful for event-driven shutdowns based on application states.

Conclusion

Spring Boot offers robust mechanisms to handle programmatic shutdowns, each with unique characteristics that cater to various application needs. By understanding these methods and their applications, developers can manage application lifecycle events effectively, ensuring a smooth, controlled shutdown procedure when necessary. Always ensure security and resource considerations are accounted for, particularly with mechanisms exposed over a network like the actuator's shutdown endpoint.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.