Threads addShutdownHook method in java


Contents of page :
  • addShutdownHook method in java >
  • Program to demonstrate addShutdownHook method >
  • Output analyzation >


addShutdownHook method in java >
  • addShutdownHook method registers a new virtual-machine shutdown hook.
  • A shutdown hook is a initialized but unstarted thread.
  • When JVM starts its shutdown it will start all registered shutdown hooks in some unspecified order and let them run concurrently.

When JVM (Java virtual machine)  shuts down >
  • When the last non-daemon thread finishes, or
  • when the System.exit is called.

Once JVM’s shutdown has begun new shutdown hook cannot be registered neither  previously-registered hook can be de-registered. Any attempt made to do any of these operations causes an IllegalStateException.


Program to demonstrate addShutdownHook method >
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class AddShutDownHookTest extends Thread{
   public static void main(String[] args) throws InterruptedException {   
          System.out.println("main thread started");
         
          Runtime.getRuntime().addShutdownHook(new Thread(){
       public void run() {
          try{
                System.out.println("executing shutdown hook");
          }catch (Exception e){
                e.printStackTrace();
          }
          System.out.println("shutdown hook executed successfully");
       }
     });
         
          Thread.sleep(4000); //Optional delay
          System.out.println("main thread ended");
   }
}
/*OUTPUT
main thread started
main thread ended
executing shutdown hook
shutdown hook executed successfully
*/

Output analyzation >
If we note output of program, added shutdown hook executed when JVM started its shutdown. And JVM started its shutdown when main thread (non-daemon) finished.
I have given optional delay of 4000 milliSec to ensure that shutDown hook executes only when main thread (non-daemon) finishes.


RELATED LINKS>



Important Thread methods (salient features, usage with programs)>

Sleep() method in threads - 10 key features with programs

Wait() and notify() methods- Definition, 8 key features, solving consumer producer problem with & without these methods and consequences of not using wait() and notify() methods.

Daemon threads - 12 salient features of Daemon Thread

2 alternate ways to stop thread, as stop() method is deprecated

Join() method - 10 salient features of join

Thread isAlive() method

interrupt() method of thread in java

holdsLock(object) method to find whether current thread holds the lock on monitor of specified object.

Thread priorities - setPriority() and getPriority() methods

Using Suspend and resume method in threads



Methods for Adding ShutdownHook and handling uncaught runtime exception >

Threads addShutdownHook method in java

Handling uncaught runtime exception generated in run method using - setDefaultUncaughtExceptionHandler method




eEdit
Must read for you :