0

In C programs using system threads for example, I can pass a SIGINT with Ctrl+C and the process will be killed silently. But when I do the same thing to a Java program with threads, locks, semaphores et cetera, the JVM just stops there and I have to kill the process "outside", by closing the terminal or rebooting the system. How can a make a Java program silently exit as it should without closing the terminal when I see some wrong behaviors in runtime?

1 Answers1

0

You can add a shutdown hook to the JVM that gets triggered when a SIGINT is received and then in there call Runtime.getRuntime().halt(0). That will kill the process. You can even use the Shutdown Hook to clean your running Threads.

[EDIT] My initial answer was to use System.exit() in the hook. But that will not work because System.exit will trigger the already running hook.

You can try this example with the hook and not registering the hook.

public class Exit {

public static void main(String[] args) {

    Runtime.getRuntime().addShutdownHook(new ExitHok());

    Thread t = new Thread(new Printer());
    t.start();

}

private static class ExitHok extends Thread {
    @Override
    public void run() {
        System.out.println("Received shutdown");
        Runtime.getRuntime().halt(0);
    }
}

private static class Printer implements Runnable {
    @Override
    public void run() {
        int counter = 0;
        while (true) {
            System.out.println(++counter);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
    }
}

}

gfelisberto
  • 1,655
  • 11
  • 18