I have a spring boot application which needs to clear or clean up the resources when we kill the process using kill pid. @predestroy annotated method is not working and not getting called. Please suggest how can we catch the SIGTERM and invoke the predestroy method
Ideally, it should work but make sure SIGTERM
is called and not SIGKILL
I have a few cases where we run spring boot application
Docker
When you execute docker stop
what happens behind the scene is
Stop one or more running containers The main process inside the container will receive SIGTERM, and after a grace period, SIGKILL
kill
kill 9955
=> SIGTERM is called
kill -9 9955
=> SIGKILL is called
Refer here for more detail on kill.
Now coming back to @PreDestroy
I have added following line in my SpringBoot Application
@PreDestroy
public void tearDown() {
System.out.println("Shutting Down...............the ");
}
I get following output when I do kill portno
2019-01-04 10:52:44.776 INFO o.s.s.c.ThreadPoolTaskScheduler / shutdown - 208 : Shutting down ExecutorService 'taskScheduler'
2019-01-04 10:52:44.783 INFO o.s.s.c.ThreadPoolTaskExecutor / shutdown - 208 : Shutting down ExecutorService 'applicationTaskExecutor'
2019-01-04 10:52:44.785 INFO o.s.o.j.LocalContainerEntityManagerFactoryBean / destroy - 597 : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-01-04 10:52:44.792 INFO c.z.h.HikariDataSource / close - 350 : HikariPool-1 - Shutdown initiated...
2019-01-04 10:52:44.800 INFO c.z.h.HikariDataSource / close - 352 : HikariPool-1 - Shutdown completed.
Shutting Down...............
As you can see in Log I have 2 Scheduler Task running and JPA Entity Manager.
On receiving SIGTERM
it closes all that first and finally call preDestory.
I am not sure what more clean up you need to do but do make sure if its already cleaned.
Shut down embedded servlet container gracefully
You can also customize and write your own shutdown gracefully hook. Refer to this good discussion and sample code on this
Restructure embedded web server packages
Pls be mindful of the sample code from above link. If you are using newer version of Springboot chances are package might be missing.
Refer this for more detail on changes methods and classes
Just small addition to @MyTwoCents answer for @PreDestroy
and Docker -> ensure to use ENTRYPOINT
instead of CMD
or RUN
- only then you will run application as a main process and SIGTERM will be sent to your application
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With