Using a shutdown hook

To gain control over when you application shuts down (eg. to close database connections), you can use the 1.3 method addShutdownHook in the Runtime class and pass it a thread object. The JVM will execute the thread when the application is about the end.


public class Main
   public static void main(String args[]) {

      Runtime.getRuntime().addShutdownHook(new Thread() {
         public void run() {
            System.out.println("Shutting down...");

      System.out.println("press ctrl-c to exit!");
      while (true) ;