Capture SIGINT in Java

Begui picture Begui · Mar 29, 2010 · Viewed 37.4k times · Source

What is the best way to capture a kill signal in java without using JNI. I did discover the sun.misc.Signal and the sun.misc.SignalHandler and the warning of the possibility of being removed in the future releases.

Would using JNI to call a c lib be the only option i have?

Answer

user177800 picture user177800 · Mar 30, 2010

The way to handle this would be to register a shutdown hook. If you use (SIGINT) kill -2 will cause the program to gracefully exit and run the shutdown hooks.

Registers a new virtual-machine shutdown hook.

The Java virtual machine shuts down in response to two kinds of events:

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or

  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

I tried the following test program on OSX 10.6.3 and on kill -9 it did NOT run the shutdown hook, didn't think it would. On a kill -15 it DOES run the shutdown hook every time.

public class TestShutdownHook
{
    public static void main(final String[] args) throws InterruptedException
    {
        Runtime.getRuntime().addShutdownHook(new Thread()
        {
            @Override
            public void run()
            {
                System.out.println("Shutdown hook ran!");
            }
        });

        while (true)
        {
            Thread.sleep(1000);
        }
    }
}

This is the documented way to write your own signal handlers that aren't shutdown hooks in Java. Be warned that the com.sun.misc packages and are un-supported and may be changed or go away at any time and probably only exist in the Sun JVM.