How to handle a SIGTERM

JavaExitSigterm

Java Problem Overview


Is there a way in Java to handle a received SIGTERM?

Java Solutions


Solution 1 - Java

Yes, you can register a shutdown hook with Runtime.addShutdownHook().

Solution 2 - Java

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

Solution 3 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartijn CourteauxView Question on Stackoverflow
Solution 1 - JavaMatthew FlaschenView Answer on Stackoverflow
Solution 2 - JavaEdward DaleView Answer on Stackoverflow
Solution 3 - JavaarcamaxView Answer on Stackoverflow