Catching SIGTERM signal in Spring

Krishna Murari
1 min readJun 10, 2020

--

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.

--

--