SIGTERM,SIGINT,SIGKILL and Java's shutdownHook 📎
The SIGTERM signal requests termination, whereby SIGKILL ...is sent to a process to cause it to terminate immediately...
A Java application behaves accordingly. The shutdown hook (shutdownListener
):
public class App {
public static void main(String[] args) {
var shutdownListener = new Thread(){
public void run(){
System.out.println("shutdown in 10s ");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {}
}
};
Runtime.getRuntime().addShutdownHook(shutdownListener);
Executors.newSingleThreadScheduledExecutor().
scheduleAtFixedRate(() -> System.out.println("."), 0, 2, TimeUnit.SECONDS);
}
}
...is executed for SIGTERM and SIGINT. The JVM executes the hook and waits, in the case above for 10 seconds, with the shutdown procedure until
the completion of the shutdownHook
.
To send a signal, you will need the process id first. The jcmd
returns PIDs from running Java processes, e.g: [PID] airhacks.App
.
kill -TERM [PID]
sends the SIGTERM (and kill -INT [PID]
SIGINT)
signal to the JVM and initiates the shutdown:
.
.
shutdown in 10s
.
.
The kill -KILL [PID]
command immediately kills the JVM, even with the running hook, and produces the following output:
[1] [PID] killed java -cp target/signals.jar airhacks.App
Also checkout kill -l
for a list of all available signals.
kubernetes (and so openshift) is using SIGTERM and after a grace period, SIGKILL signals to kill containers in a POD.