Spring Boot
shutdown hook
application lifecycle
graceful shutdown
Java

Spring Boot shutdown hook

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

Spring Boot is a powerful framework that simplifies the development of Java applications. One of its lesser-known yet crucial features is the "Shutdown Hook," which ensures that resources are gracefully released when an application is terminated. This feature is especially important for long-lived applications that interact with external resources, such as databases, file systems, or messaging services.

Understanding the Need for a Shutdown Hook

Before diving into how Spring Boot implements a shutdown hook, it's important to understand why a shutdown hook is necessary. When a Java application is abruptly terminated, resources it uses can be left in an undefined state. This not only leads to memory leaks but can also cause data corruption. A shutdown hook provides a mechanism to release these resources safely.

Spring Boot's Implementation of Shutdown Hook

Spring Boot offers a convenient way to manage shutdown hooks through its ApplicationContext. By default, when a Spring Boot application is closed, the ApplicationContext ensures:

  • Beans marked with @PreDestroy are properly destroyed.
  • Any remaining tasks or processes are completed.
  • Connections are properly closed.
java
1import org.springframework.boot.SpringApplication;
2import org.springframework.boot.autoconfigure.SpringBootApplication;
3
4@SpringBootApplication
5public class Application {
6
7    public static void main(String[] args) {
8        SpringApplication.run(Application.class, args);
9    }
10}

In this example, the SpringApplication.run() method initializes the ApplicationContext, which implicitly registers a shutdown hook to ensure clean termination of the application.

Customizing the Shutdown Hook

In some cases, the default shutdown procedure may not be sufficient. For example, you might need to release custom resources or perform specific actions before the application shuts down. In such cases, you can add your shutdown logic using beans annotated with @PreDestroy.

java
1import javax.annotation.PreDestroy;
2import org.springframework.stereotype.Component;
3
4@Component
5public class CustomShutdownHook {
6
7    @PreDestroy
8    public void onShutdown() {
9        // Custom shutdown logic
10        System.out.println("Performing custom shutdown tasks.");
11    }
12}

Graceful Shutdown

Starting with Spring Boot 2.3, a new feature called Graceful Shutdown was introduced, allowing the application to finish processing current requests before terminating. This is particularly useful for web applications to ensure all HTTP requests are completed.

To enable Graceful Shutdown, modify the application.properties:

properties
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=30s

The server.shutdown=graceful property switches the shutdown behavior to a graceful mode, while spring.lifecycle.timeout-per-shutdown-phase specifies the maximum time allocated to shutdown phases.

Impact on Health Checks

During the shutdown process, especially when using Graceful Shutdown, applications might still respond to health checks. It's crucial to set up health endpoint behavior that works in tandem with the shutdown process to avoid false positives or negatives in status reporting systems.

Here's an example of customizing health checks with Actuator:

properties
management.health.probes.enabled=true

With this configuration, Actuator will adjust health checks based on the application's readiness and liveness states during shutdown.

Key Points Summary

FeatureDescriptionDefault Behavior/Setting
Default ShutdownSpring Boot automatically registers a shutdown hook.Ensures bean destruction and context closure.
Custom ShutdownExtend shutdown logic with @PreDestroy.Add components to perform custom tasks.
Graceful ShutdownWaits for active tasks to complete on shutdown.Disabled by default; enable via properties.
Health ChecksIntegrate with Actuator for health status updates.Use Actuator's probes for readiness/liveness.

Conclusion

In modern application development, especially in cloud-native environments, managing shutdown procedures is integral to maintaining application stability and data integrity. Spring Boot's robust shutdown hooks and customizable features give developers the tools to manage application lifecycle events gracefully. By configuring and extending these hooks, it's possible to ensure that resources are released properly, avoiding potential pitfalls associated with abrupt application termination.

By understanding and effectively utilizing these features, developers can create resilient applications that handle shutdowns gracefully, leading to cleaner transitions and fewer resource leaks, ultimately resulting in more reliable software systems.


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.