You are on page 1of 12
‘21rame2, 11:89 PM «Java ShutdownHook- javatpoint tps: ww javatpointcom/ShuldownHook-thread ne ‘21rame2, 11:89 PM «Java ShutdownHook- javatpoint Java Shutdown Hook A special construct that facilitates the developers to add some code that has to be run when the Java Virtual Machine (JVM) is shutting down is known as the Java shutdown hook. The Java shutdown hook comes in very handy in the cases where one needs to perform some special cleanup work when the JVM is shutting down, Note that handling an operation such as invoking a special method before the JVM terminates does not work using a general construct when the JVM is shutting down due to some external factors. For example, whenever a kill request is generated by the operating system or due to resource is not allocated because of the lack of free memory, then in such a case, it is not possible to invoke the procedure. The shutdown hook solves this problem comfortably by providing an arbitrary block of code. Taking at a surface level, learning about the shutdown hook is straightforward. All one has to do is to derive a class using the java.lang.Thread class, and then provide the code for the task one wants to do in the run() method when the JVM is going to shut down, For registering the instance of the derived class asthe — shutdown ~—hook,-—sone-— has to._—invoke_~—the_-—smethod Runtime.getRuntime(.addShutdownHook(Thread), whereas for removing the already registered shutdown hook, one has to invoke the removeShutdownHook(Thread) method. In nutshell, the shutdown hook can be used to perform cleanup resources or save the state when JVM shuts down normally or abruptly. Performing clean resources means closing log files, sending some alerts, or something else. So if you want to execute some code before JVM shuts down, use the shutdown hook. When does the JVM shut down? The JVM shuts down when: hnps:iwwwijavalpoin com/ShuldownHook-thread ana ‘21rame2, 11:89 PM «Java ShutdownHook- javatpoint © user presses ctrl+c on the command prompt ©. System.exit(int) method is invoked © user logoff © user shutdown ete, The addShutdownHook(Thread hook) method The addShutdownHook() method of the Runtime class is used to register the thread with the Virtual Machine. Syntax: public void addShutdownHook(Thread hook){} The object of the Runtime class can be obtained by calling the static factory method getRuntime() For example Runtime r = Runtime.getRuntime); The removeShutdownHook(Thread hook) method The removeShutdownHook() method of the Runtime class is invoked to remove the registration of the already registered shutdown hooks. Syntax: public boolean removeShutdownHook(Thread hook){ } True value is returned by the method, when the method successfully de-register the registered hooks; otherwise returns false. Factory method The method that returns the instance of a class is known as factory method. hnps:iwwwijavalpoin com/ShuldownHook-thread ana ‘21rame2, 11:89 PM «Java ShutdownHook- javatpoint Simple example of Shutdown Hook FileName: MyThread java class MyThread extends Thread{ public void rund{ System.out.printin(“shut down hook task completed..”); public class TestShutdown1 public static void main(Stringl] args)throws Exception { Runtime r=Runtime.getRuntime(); raddShutdownHook(new MyThread(); System.out printin(’Now main sleeping... press ctrl +c to exit"); try(Thread sleep(3000);}catch (Exception e) {) } ) Output: Now main sleeping. s ctrl+c to exit shut down hook task completed. hnps:iwwwijavalpoin com/ShuldownHook-thread ana ‘21rame2, 11:89 PM «Java ShutdownHook- javatpoint Same example of Shutdown Hook by anonymous class: Name: TestShutdown2,java public class TestShutdown2( public static void main(String] args)throws Exception ( Runtime r=Runtime.getRuntime(; raddShutdownHook(new Thread()( public void rund{ System.out printin(‘shut down hook task completed.."); ) System.out.printin(’Now main sleeping... press ctrl +c to exit"); try(Thread.sleep(3000);}catch (Exception e) {) ) ) Output: Now main sleeping... press ctr1+c to exit shut down hook task completed. Removing the registered shutdown hook example The following example shows how one can use the removeShutdownHook() method to remove the registered shutdown hook. FileName: RemoveHookExample java hnps:iwwwijavalpoin com/ShuldownHook-thread siz ‘21rame2, 11:89 PM «Java ShutdownHook- javatpoint class RemoveHookExample // the Msg class is derived from the Thread class static class Msg extends Thread { public void rung { System.out.printin(“Bye .."); ) ) // main method public static void main(String{] argvs) { try ( // creating an object of the class Msg Msg ms = new Msgi // registering the Msg object as the shutdown hook Runtime.getRuntime().addShutdownHook(ms); hnps:iwwjavatpoin com/ShuldownHook-thread enz ‘21rame2, 11:89PM // printing the current state of program «Java ShutdownHook- javatpoint System.out printin(“The program is beginning ..."); // causing the thread to sleep for 2 seconds ‘System.out printin("Waiting for 2 seconds Thread.sleep(2000); // removing the hook Runtime.getRuntime().removeShutdownHook(ms); // printing the message program is terminating System.out printin("The program is terminating . ) catch (Exception ex) ( exprintStackTrace(); ) ) ) Output: The program is beginning ds. Waiting for The pro s terminating Points to Remember There are some important points to keep in mind while working with the shutdown hook No guarantee for the execution of the shutdown hooks: The first and the most important thing to keep in mind is that there is no certainty about the execution of the shutdown hook. in some scenarios, the shutdown hooks will not execute at all. For example, if the JVM gets crashed due to some internal error, then there is no scope for the shutdown hooks, When the operating system gives the SYSKILL signal, then also it is not possible for the shutdown hooks to come into picture. hnps:iwwwijavalpoin com/ShuldownHook-thread m2 ‘21rame2, 11:89 PM «Java ShutdownHook- javatpoint Note that when the application is terminated normally the shutdown hooks are called (all threads of the application is finished or terminated). Also, when the operating system is shut down or the user presses the ctrl + c the shutdown hooks are invoked. Before completion, the shutdown hooks can be stopped forcefully: It is a special case of the above discussed point. Whenever a shutdown hooks start to execute, one can forcefully terminate it by shutting down the system. In this case, the operating system for a specific amount of time If the job is not done in that frame of time, then the system has no other choice than to forcefully terminate the running hooks. There can be more than one shutdown hooks, but there execution order is not guaranteed: The JVM can execute the shutdown hooks in any arbitrary order. Even concurrent execution of the shutdown hooks are also possible Within shutdown hooks, it is not allowed to unregister or register the shutdown hooks: When the JVM initiates the shutdown sequence, one can not remove or add more any existing shutdown hooks. If ‘one tries to do so, the IllegalStateException is thrown by the JVM The Runtime.halt) can stop the shutdown sequence that has been started: Only the Runtime.halt(, which terminates the JVM forcefully, can stop the started shutdown sequence, which also means that invoking the System.exit) method will not work within a shutdown hook. Security permissions are required when using shutdown hooks: If one is using the Java Security Managers, then the Java code that is responsible for removing or adding the shutdown hooks need to get the shutdown hooks permission at the runtime. If one invokes the method without getting the permission in the secure environment, then it will raise the SecurityException. Prev Next hnps:iwwwijavalpoin com/ShuldownHook-thread ana ‘21rame2, 11:89 PM «Java ShutdownHook- javatpoint w Youtube For Videos Join Our Youtube Channel: Join Now Feedback © Send your Feedback to feedback@javatpoint.com Help Others, Please Share Learn Latest Tutorials ASplunk tutorial IPSS tutorial 4} Swagger Splunk spss acorial ‘Swagger hnps:iiwwijavatpoin com/ShuldownHook-thread T-SQL tutorial Transact-SQL. one s21rain2, 11:89PM Tumblr tutorial Tumblr AR Programming tutorial R Programming 2 Python Pillow # React tutorial ReactlS ARIS tutorial RxlS #2 Python Turtle tutorial tutorial Python Pillow Python Turtle Preparation w Aptitude # _ Logical Aptude Reasoning Reasoning 2 Company Interview Questions Company Questions Trending Technologies 2 Attificial Intelligence Amtificial Intelligence LAAWS Tutorial AWS hnps:iiwwijavatpoin com/ShuldownHook-thread Java ShutdownHook- javatpoint Regex tutorial Regex #) React Native tutorial React Native #Keras tutorial Keras (pNerbal Ability Verbal Ability 2) Selenium tutorial Selenium i) Reinforcement learning tutorial Reinforcement Leaming (4) Python Design Patterns Python Design Pattems i} Interview Questions Interview Questions i Cloud ‘Computing Cloud Computing sone ‘2122122, 1:48 PM {2Hadoop tutorial Hadoop 2 Blockchain Tutorial Blockchain B.Tech / MCA DBMS tutorial DBMS 2 Computer Network tutorial Computer Network #Ethical Hacking Ethical Hacking 2 ReactIS Tutorial Reacts (eGit Tutorial Git Data Structures tutorial Data Structures 2 Compiler Design tutorial Compiler Design Computer Graphics Tutorial Computer Graphiies hnps:iiwwijavalpoin. com/ShuldownHook-thread Java ShutdownHook- javatpoint #) Data Science ‘Tutorial Data Science 2 Machine ‘Learning Tutorial Machine Learning DAA tutorial DAA 2) Computer ‘Organization and Architecture Computer Organization 2) Software Engineering Software Engineering i Angular 7 Tutorial Angular 7 2 _Devops Tutorial DevOps B Operating System Operating System B__ Discrete Mathematics Tutorial Discrete Mathematics (htm! tutorial Web Technology ane sara, 149 6M Cyber Security tutorial Cyber Security #3ava tutorial Java 2 Control ‘Systems tutorial Control System Automata, Tutorial Automata Net Framework ‘tutorial Net Data Mining Tutorial Data Mining hnps:iwwwijavalpoin com/ShuldownHook-thread «Java ShutdownHook- javatpoint 2 C Language 2C+ tutorial tutorial cH Programming Python tutorial =} List of Pathon Programs Programs 2 Data Warehouse Tutorial Data Warehouse rane

You might also like