Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Shutdown Hook in Java

  • Shutdown hooks serve as a unique mechanism that empowers developers to incorporate code that will be executed upon the shutdown of the Java Virtual Machine (JVM). This functionality proves to be invaluable when specific cleanup operations are required following the termination of the VM.
    • Handling this using general constructs such as ensuring that we call a special procedure before the application exits (calling System.exit(0)) will not work in situations where the VM is shutting down due to an external reason (for example, a kill request from the operating system) or a resource problem (out of memory). As we will see shortly, shutdown hooks easily solve this problem by allowing us to provide an arbitrary code block that the JVM will call when it is shutting down.
Table Of Content

  • Shutdown Hook in Java
  • addShutdownHook(Thread hook) method
  • removeShutdownHook(Thread hook) method
  • Shutdown Hook by anonymous class
  • Important point of Shutdown Hook


  • A thread is authorized to retrieve information pertaining to its own thread group, while it is prohibited from accessing data associated with other thread groups or its parent thread group.




  • On the surface, using a shutdown hook appears to be very simple.The process involves creating a class that extends the java.lang.Thread class and implementing the desired logic within the public void run() method, which will be executed when the virtual machine (VM) shuts down. To register this class as a shutdown hook, we simply need to call the addShutdownHook(Thread) method of the Runtime class obtained through the getRuntime() method. If there is a need to unregister a previously registered shutdown hook, the Runtime class provides the removeShutdownHook(Thread) method.

addShutdownHook(Thread hook) method

  • The Runtime class's addShutdownHook() method is used to register the thread with the Virtual Machine.
  • Syntax :
    public void addShutdownHook(Thread hook){}  

removeShutdownHook(Thread hook) method

  • To remove the registration of previously registered shutdown hooks, the Runtime class's removeShutdownHook() method is called.
  • Syntax :
    public boolean removeShutdownHook(Thread hook){ }    





class shutDownDemo extends Thread{
	public void run(){    
        System.out.println("Shutdown Hook is running");    
    }    
}
public class Main{
    public static void main(String arg[]) {
	 Runtime runtime=Runtime.getRuntime();    
	 runtime.addShutdownHook(new shutDownDemo());            
	 System.out.println("Press Ctrl+c to Terminate");    
	 try{
		Thread.sleep(3000);
	 }catch (Exception e) {
		e.printStackTrace();
	 }    
   }
}

Output:

Press Ctrl+c to Terminate
Shutdown Hook is running 

Shutdown Hook by anonymous class




public class Main{
    public static void main(String arg[]) {
	 Runtime runtime=Runtime.getRuntime();    
	 runtime.addShutdownHook(new Thread(){  
	 public void run(){    
        System.out.println("Shutdown Hook is running");    
     } 
	 });
	 System.out.println("Press Ctrl+c to Terminate");    
	 try{
		Thread.sleep(3000);
	 }catch (Exception e) {
		e.printStackTrace();
	 }    
   }
}

Output:

Press Ctrl+c to Terminate
Shutdown Hook is running 

Important point of Shutdown Hook

  • There is no guarantee that the shutdown hooks will be executed: The first and most important thing to remember is that the shutdown hook's execution is not guaranteed. In some cases, the shutdown hooks will never be executed. For example, if the JVM crashes due to an internal error, the shutdown hooks are rendered ineffective. When the operating system sends the SYSKILL signal, the shutdown hooks are also prevented from being used.
  • It should be noted that when the application is normally terminated, the shutdown hooks are called (all threads of the application is finished or terminated). Additionally, the shutdown hooks are invoked when the operating system is shut down or the user presses ctrl + c.



  • The shutdown hooks can be forced to stop before completion It is a subset of the previously discussed point. When a shutdown hook begins to execute, it can be forced to stop by shutting down the system. In this case, the operating system for a predetermined period of time. If the job is not completed within that time frame, the system is forced to terminate the running hooks.
  • Multiple shutdown hooks can be defined, but the order in which they are executed by the JVM is not predetermined. The execution of shutdown hooks may occur in any sequence, potentially running concurrently.
  • It is important to note that unregistering or registering shutdown hooks within other shutdown hooks is not allowed. When the JVM starts the shutdown process, it does not permit the removal or addition of any existing shutdown hooks. Any attempt to do unregistering or registering shutdown hooks will result in an IllegalStateException being thrown by the JVM.
  • The shutdown sequence can be terminated using Runtime.halt(): Only the Runtime.halt() method, which forcefully terminates the JVM, can halt the shutdown sequence, which also means that invoking the System.exit() method within a shutdown hook will fail.
  • When using shutdown hooks, the following security permissions are required: If the Java Security Managers are used, the Java code responsible for removing or adding shutdown hooks must obtain shutdown hooks permission at runtime. If the method is invoked without permission in a secure environment, the SecurityException is thrown.

Multitasking vs Multithreading Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class

Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.