Class ShutdownHook

  • All Implemented Interfaces:
    Runnable

    public final class ShutdownHook
    extends Thread
    Provides a simple way for an console-based, Java application main thread to wait until the virtual machine terminates. If an application main method is solely responsible for setting up and tearing down the application and hands off control to another thread between the two, then the main thread must block until it is time to stop. This class is a Java shutdown hook, returning a CountDownLatch on which the main thread waits. This latch is decremented when the Java Runtime executes the shutdown hook. Since the latch is size one, CountDownLatch.await() will return.

    This returned latch may be passed to other objects which can decrement the latch and so signal that the application is to terminate.

    An example Java main method uses this class as follows:

       
     import java.util.concurrent.CountDownLatch;
    
     public static void main(final String args[])
     {
         // 1. Check the command line arguments.
         // 2. Initialize the application.
         // 3. Set up the shutdown hook.
         final CountDownLatch signal = ShutdownHook.addShutdownHook();
    
         // 4. Start application thread.
         // 5. Wait for the JVM to stop.
         try {
             signal.await();
         } catch (InterruptedException interrupt) {}
    
         // 6. Tear down the application.
     }
       
     
    Author:
    Charles Rapp
    • Method Detail

      • addShutdownHook

        public static CountDownLatch addShutdownHook()
        Returns the signal used by the shutdown hook to notify the caller when the JVM is shutdown. If the shutdown hook does not exist, then creates it and adds it to the default system runtime. The count down latch size is one, which means that CountDownLatch.await() returns as soon as this latch is decremented.
        Returns:
        the shutdown hook signal.
      • removeShutdownHook

        public static void removeShutdownHook()
        Unhooks the shutdown hook instance from the system runtime.