Teachnique
      CourseRoadmaps
      Login

      OverviewHistoryFeaturesJava 8 - New Featuresvs C++Virtual Machine(JVM)JDK vs JRE vs JVMHello World ProgramEnvironment SetupBasic SyntaxVariable TypesData TypesType CastingUnicode SystemBasic OperatorsCommentsStreamsNew Date-Time API

      Loop ControlDecision Makingif-else Statementswitch statementfor loopfor each Loopwhile Loopdo...while Loopbreak Statementcontinue Statement

      OOPs (Object-Oriented Programming) ConceptsObject and ClassesClass AttributesClass MethodsMethodsVariable ScopesConstructorsAccess ModifiersInheritanceAggregationPolymorphismOverridingMethod OverloadingDynamic BindingStatic BindingInstance Initializer BlockAbstractionEncapsulationInterfacesPackagesInner classesStatic ClassesAnonymous ClassesSingleton ClassWrapper ClassesEnum Class

      Number ClassBoolean classCharacter ClassArraysMath Class

      File ClassCreating FilesWrite To FilesReading FileDelete FilesDirectory OperationsFiles and I/O

      ExceptionsTry Catch BlockTry with ResourcesMultiple Catch BlocksNested Try BlockFinally BlockThrows and Throw | Throw an ExceptionException PropagationBuilt-in ExceptionsCustom Exception

      MultithreadingThread Life CycleCreating a ThreadStarting a ThreadJoining ThreadsNaming a Thread with ExamplesScheduling Threads with ExamplesThread PoolsMain ThreadThread PriorityDaemon ThreadThreadGroup ClassJVM Shutdown Hook

      Thread SynchronizationBlock SynchronizationStatic SynchronizationInter Thread CommunicationThread DeadlockInterrupting ThreadThread ControlReentrant Monitor

      NetworkingSocket ProgrammingURL ProcessingURL ClassURLConnection ClassHttpURLConnection ClassSocket Class with ExamplesGenerics

      Collections FrameworkCollection Interface

      List InterfaceArrayList Class

      Queue InterfaceArrayDeque Class

      Map InterfaceSortedMap Interface

      Set InterfaceSortedSet Interface

      Data Structures Enumeration Interface BitSet Class

      How to Use Iterator?How to Use Comparator?How to Use Comparable?

      RecursionRegular ExpressionsSerializationString ClassJava Arrays - Class

      Feedback

      Submit request if you have any questions.

      Course
      JVM Shutdown Hook

      Java Tutorial

      This Java tutorial is tailored for newcomers, offering a journey from basic principles to complex Java programming techniques. Completing this tutorial equips you with a solid understanding of Java, preparing you for advanced learning. You'll emerge ready to tackle the challenges of becoming a top-tier software engineer, with the skills to innovate and excel in the vast world of software development.

      JVM Shutdown Hook

      JVM Shutdown

      The following are the two different ways for JVM shutdown
      • A controlled process: JVM starts to shut down its process if the System.exit() method is called, CTRL+C is pressed, or if the last non-daemon thread terminates.
      • An abrupt manner: JVM starts to shut down its process if it receives a kill signal, the Runtime.getRuntime().halt() method is called, or any kind of OS panic.

      JVM Shutdown Hook

      A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking the exit method.

      JVM Shutdown Hook: The addShutdownHook(Thread hook) Method

      The Runtime addShutdownHook(Thread hook) method registers a new virtual-machine shutdown hook.

      Declaration

      Following is the declaration for java.lang.Runtime.addShutdownHook() method
      public void addShutdownHook(Thread hook)

      Parameters

      hook − An initialized but unstarted Thread object.

      Return Value

      This method does not return a value.

      Exception

      • IllegalArgumentException − If the specified hook has already been registered, or if it can be determined that the hook is already running or has already been run.
      • IllegalStateException − If the virtual machine is already in the process of shutting down.
      • SecurityException − If a security manager is present and it denies RuntimePermission("shutdownHooks").

      Example of JVM Shutdown Hook

      In this example, we're creating a class CustomThread by extending Thread class. This thread object will be used as JVM Shutdown hook. CustomThread class has run() method implementation. In main class TestThread, we've added a shutdown hook using Runtime.getRuntime().addShutdownHook() method, by passing it a thread object. In output you can verify that CustomThread run() method is called when program is about to exit.
      package com.tutorialspoint;
      
      class CustomThread extends Thread {
      public void run() {
      System.out.println("JVM is shutting down.");
      }
      }
      
      public class TestThread {
      public static void main(String args[]) throws InterruptedException {
      try {
      // register CustomThread as shutdown hook
      Runtime.getRuntime().addShutdownHook(new CustomThread());
      // print the state of the program
      System.out.println("Program is starting...");
      // cause thread to sleep for 3 seconds
      System.out.println("Waiting for 3 seconds...");
      Thread.sleep(3000);
      // print that the program is closing
      System.out.println("Program is closing...");
      } catch (Exception e) {
      e.printStackTrace();
      }
      }
      }

      Output

      Program is starting...
      Waiting for 3 seconds...
      Program is closing...
      JVM is shutting down.

      More Example of JVM Shutdown Hook

      Example 1

      In this example, we're creating a class CustomThread by implementing Runnable interface. This thread object will be used as JVM Shutdown hook. CustomThread class has run() method implementation. In main class TestThread, we've added a shutdown hook using Runtime.getRuntime().addShutdownHook() method, by passing it a thread object. In output you can verify that CustomThread run() method is called when program is about to exit.
      package com.tutorialspoint;
      
      class CustomThread implements Runnable {
      public void run() {
      System.out.println("JVM is shutting down.");
      }
      }
      
      public class TestThread {
      public static void main(String args[]) throws InterruptedException {
      try {
      // register CustomThread as shutdown hook
      Runtime.getRuntime().addShutdownHook(new Thread(new CustomThread()));
      // print the state of the program
      System.out.println("Program is starting...");
      // cause thread to sleep for 3 seconds
      System.out.println("Waiting for 3 seconds...");
      Thread.sleep(3000);
      // print that the program is closing
      System.out.println("Program is closing...");
      } catch (Exception e) {
      e.printStackTrace();
      }
      }
      }

      Output

      Program is starting...
      Waiting for 3 seconds...
      Program is closing...
      JVM is shutting down.

      Example 2

      We can remove the shutdown hook as well using removeShutdownHook(). In this example, we're creating a class CustomThread by implementing Runnable interface. This thread object will be used as JVM Shutdown hook. CustomThread class has run() method implementation. In main class TestThread, we've added a shutdown hook using Runtime.getRuntime().addShutdownHook() method, by passing it a thread object. As last statement, we're removing the hook using Runtime.getRuntime().removeShutdownHook() method
      package com.tutorialspoint;
      
      class CustomThread implements Runnable {
      public void run() {
      System.out.println("JVM is shutting down.");
      }
      }
      
      public class TestThread {
      public static void main(String args[]) throws InterruptedException {
      try {
      Thread hook = new Thread(new CustomThread());
      // register Message as shutdown hook
      Runtime.getRuntime().addShutdownHook(hook);
      // print the state of the program
      System.out.println("Program is starting...");
      // cause thread to sleep for 3 seconds
      System.out.println("Waiting for 3 seconds...");
      Thread.sleep(3000);
      // print that the program is closing
      System.out.println("Program is closing...");
      Runtime.getRuntime().removeShutdownHook(hook);
      } catch (Exception e) {
      e.printStackTrace();
      }
      }
      }

      Output

      Program is starting...
      Waiting for 3 seconds...
      Program is closing...