Graceful Shutdown & Spring Boot

Graceful Shutdown & Spring Boot


1






Rahul Kumar (@rahul)

Whether you're an experienced Spring Boot developer or just starting your journey, this guide provides valuable knowledge and hands-on examples to help you navigate the technical debt of application reliability and the art of graceful shutdowns in Spring Boot.

I am assuming that you already know Java & Spring Boot

What is graceful shutdown?

Graceful shutdown refers to the process of stopping a software application or service in a way that allows it to complete its ongoing tasks and operations before shutting down. This approach ensures that the application finishes any pending processes, handles ongoing transactions, and releases resources properly, finished logging.

The PreDestroy annotation is used on methods as a callback notification to signal that the instance is in the process of being removed by the container. The method annotated with PreDestroy is typically used to release resources that it has been holding. 

You can check the rules for using this annotation here

      package com.dsabyte;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Service;
import java.time.Instant;

@Service
public class DsaByte {
  @PreDestroy
  public void preDestroy() throws InterruptedException {
    System.out.println("Cleaning Resource: " + Instant.now());
    Thread.sleep(1000); // simulate an asynchronous cleaning
    System.out.println("Cleaned Resource: " + Instant.now());
  }
}

    

We have created a class named DsaByte and a method preDestroy. We have added @Service annotation on the class level so that Spring Boot can recognise it. We have added @PreDestroy annotation on the preDestroy method so that it can be invoked by the container on any termination event received on the container level. 

When you run the above code, you'll get to the following output

      Cleaning Resource: 2023-11-16T00:31:28.863389Z
Cleaned Resource: 2023-11-16T00:31:29.868606Z
    

Add a thoughtful comment...

✨ Explore more tech insights and coding wonders with @dsabyte! Your journey in innovation has just begun. Keep learning, keep sharing, and let's continue to code a brighter future together. Happy exploring! 🚀❤️

  • #java
  • #spring-boot
  • #shutdown
  • #@dsabyte
  • #graceful-degradation

Subscribe to our newsletter.

Join the "News Later" community by entering your email. It's quick, it's easy, and it's your key to unlocking future tech revelations.

Weekly Updates

Every week, we curate and deliver a collection of articles, blogs and chapters directly to your inbox. Stay informed, stay inspired, and stay ahead in the fast-paced world of technology.

No spam

Rest assured, we won't clutter your inbox with unnecessary emails. No spam, only meaningful insights, and valuable content designed to elevate your tech experience.

© 2024 @dsabyte. All rights reserved