Is there a way in Java to handle a received SIGTERM?
Asked
Active
Viewed 5.9k times
3 Answers
83
Yes, you can register a shutdown hook with Runtime.addShutdownHook()
.

Matthew Flaschen
- 278,309
- 50
- 514
- 539
-
2Would that hook be also triggered also when `System.exit(1)` is performed elsewhere?. I am trying to follow this pattern to handle controlled stop for my multithread Java program and I find that `System.exit(1)` is not terminating the JVM. – M.E. Nov 19 '19 at 03:44
-
@M.E. yes they are. See the documentation for Runtime.exit (which is called by System.exit) here: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Runtime.html#exit(int) – erwaman Jun 08 '20 at 14:57
63
You could add a shutdown hook to do any cleanup.
Like this:
public class myjava{
public static void main(String[] args){
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("Inside Add Shutdown Hook");
}
});
System.out.println("Shut Down Hook Attached.");
System.out.println(5/0); //Operating system sends SIGFPE to the JVM
//the JVM catches it and constructs a
//ArithmeticException class, and since you
//don't catch this with a try/catch, dumps
//it to screen and terminates. The shutdown
//hook is triggered, doing final cleanup.
}
}
Then run it:
el@apollo:~$ javac myjava.java
el@apollo:~$ java myjava
Shut Down Hook Attached.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at myjava.main(myjava.java:11)
Inside Add Shutdown Hook

beerbajay
- 19,652
- 6
- 58
- 75

Edward Dale
- 29,597
- 13
- 90
- 129
-
This is for the entire system shutdown though. While it works in most cases, ideal would be if it worked on the inherited process. – mjs Jun 01 '20 at 21:46
5
Another way to handle signals in Java is via the sun.misc.signal package. Refer to http://www.ibm.com/developerworks/java/library/i-signalhandling/ for understanding how to use it.
NOTE: The functionality being within sun.* package would also mean that it may not be portable/behave-the-same across all OS(s). But you may want to try it out.

Thorbjørn Ravn Andersen
- 73,784
- 33
- 194
- 347

arcamax
- 610
- 1
- 7
- 14
-
-
3Nope - not exactly. The signal handling API I mentioned can be used to handle most of the Native OS signals (trap, intr, kill, etc) within Java Apps. On the other hand ShutdownHook gets invoked only when JVM is finally terminating (after a kill signal is received). – arcamax Jun 14 '10 at 08:41
-
1Yeah looks like IBM developer works have gone through a website migration. The link no longer works. – arcamax May 30 '14 at 15:44
-
Concerning the broken link to the sun.misc.signal package, see http://stackoverflow.com/questions/19711062/alternative-to-sun-misc-signal – Daniel Mar 29 '15 at 21:46
-
Also never use sun classes - newer JDKs will bite you for doing it and your code won't run. – Ethan McCue Oct 01 '20 at 02:17