Trapping CTRL-C in a Java app

The method addShutdownHook() of the java.lang.Runtime class provides a way of trapping a shutdown of the virtual machine. Please not that this method was added since java version 1.3.

The method expects one argument and that is a Thread object. This thread will be started when the virtual machine terminates. The only way this code will not be executed is when you use the method Runtime.halt().
After you have added a Shutdown hook, it is also possible to remove it with the equivalent method removeShutdownHook(). Its parameter should be the same as the one passed in addShutdownHook.

The following code illustrates an example that makes use of the addShutdownHook method.

Main.java:

// The Shutdown class is a sample class to illustrate the
// use of the addShutdownHook method
class Shutdown {
  private Thread thread = null;
 
  public Shutdown() {
    thread = new Thread("Sample thread") {
      public void run() {
        while (true) {
          System.out.println("[Sample thread] Sample thread speaking...");
          try {
            Thread.currentThread().sleep(1000);
          } catch (InterruptedException ie) {
            break;
          }
        }
        System.out.println("[Sample thread] Stopped");
      }
    };
    thread.start();
  }

  public void stopThread() {
    thread.interrupt();
  }
}
 
 
// The ShutdownThread is the thread we pass to the
// addShutdownHook method
class ShutdownThread extends Thread {
  private Shutdown shutdown = null;
 
  public ShutdownThread(Shutdown shutdown) {
    super();
    this.shutdown = shutdown;
  }
  
  public void run() {
    System.out.println("[Shutdown thread] Shutting down");
    shutdown.stopThread();
    System.out.println("[Shutdown thread] Shutdown complete");
  }
}
 
 
// And finally a Main class which tests the two classes
// We let the sample thread run for 10 seconds and then
// force a Shutdown with System.exit(0). You may stop the
// program early by pressing CTRL-C.
public class Main {
  public static void main(String [] args) {
    Shutdown shutdown = new Shutdown();
    try {
      Runtime.getRuntime().addShutdownHook(new ShutdownThread(shutdown));
      System.out.println("[Main thread] Shutdown hook added");
    } catch (Throwable t) {
      // we get here when the program is run with java
      // version 1.2.2 or older
      System.out.println("[Main thread] Could not add Shutdown hook");
    }
 
    try {
      Thread.currentThread().sleep(10000);
    } catch (InterruptedException ie) {
    }
    System.exit(0);
  }
}