Catching SIGTERM signal in Spring

This story is about how to catch SIGTERM in spring and allowing pending/already running operations to finish gracefully

What is SIGTERM?

The SIGTERM signal is a generic signal used to cause program termination. Unlike SIGKILL, this signal can be blocked, handled, and ignored. It is the normal way to politely ask a program to terminate.

How to catch it?

There are several events registered in spring which are raised for ApplicationContext . One of them is ContextClosedEvent.One needs to implement a listener to this event like below. Then only thing you will need is to finish your tasks in onApplicationEvent(ContextClosedEvent event) which would rather have been failed.

public class AppCloseEventListener implements ApplicationListener<ContextClosedEvent> {

@Override
public void onApplicationEvent(ContextClosedEvent event) {

}
}

Note : If you are using K8s , you will need to make sure to set graceTerminationPeriod to some value in which your task must get complete.GraceTerminationPeriod is the time after which k8s sends SIGKILL to abruptly kill the pod.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store