Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Getting Started
2.1.
Example 1
2.2.
Output
2.3.
Example 2
2.4.
Output
3.
Working Principles 
4.
Frequently Asked Questions
5.
Conclusion
Last Updated: Mar 27, 2024

Shutdown Hook

Author Aman Thakur
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

Shutdown Hooks are a specific construct that allows developers to insert code that will run when the JVM shuts down. This is useful in situations when we need to do extra clean-up actions before the VM shuts down.

In scenarios when the VM is shutting down due to an external reason (for example, a kill request from the operating system) or a resource problem, generic constructs such as guaranteeing that we execute a particular method before the programme departs (calling System.exit(0)) will not function (out of memory).  As we'll see shortly, Shutdown hooks easily fix this problem by letting us give an arbitrary code block that the JVM(Java Virtual Machine) will call when it's shutting down.

Using a shutdown hook looks to be straightforward on the surface. We'll have to make a class that extends the java.lang package. Put the logic we want to perform when the VM goes down in the public void run() method of the Thread class. Then, using, we register a VM shutdown hook with an instance of this class.

addShutdownHook(Thread) function of Runtime.getRuntime(). The Runtime class also has a removeShutdownHook(Thread) function if you need to delete a previously registered shutdown hook.

Now let see its implementation with some practical examples which are mentioned below

Must Read, Multithreading in java, Duck Number in Java, Multithreading in Python

Getting Started

Let's code it out and find the output and see how simple is it to write a ShutDown Hook in java and see its application.

Example 1

public class ShutDownHook{
   public static void main(String[] args){
       Runtime.getRuntime().addShutdownHook(new Thread(){
           public void run(){
               System.out.println("*** Coding Ninjas ***");
               System.out.println("Shut Down Hook was running !!");
           }
       });

       System.out.println("Application has been terminated!!");
   }
}

Output

Example 2

import java.util.ArrayList;

class ChildThread extends Thread{
   public void run(){
       System.out.println("\nClean Up code");
       System.out.println("ShutDown Hook");
   }
}

public class ShutDownHook{
   public static void main(String[] args){
       Runtime current = Runtime.getRuntime();
       current.addShutdownHook(new ChildThread());

       ArrayList<Integer> numbers = new ArrayList<Integer>();

           numbers.add(1);
           numbers.add(5);
           numbers.add(7);

       System.out.print("Squares of Integers: ");
       numbers.forEach((number) -> {System.out.print(number * number + " ");});
   }
}

Output

Try it on online java compiler.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Working Principles 

While it is very straightforward to construct a shutdown hook, understanding the internals of shutdown hooks is required in order to make effective use of them. As a result, we'll look at some of the 'gotchas' in the shutdown hook design in this post.

 

1. In some instances, ShutDown hooks may not be performed, here are a few which is mentioned below:
The first thing to remember is that shutdown hooks are not always guaranteed to run.

If the JVM crashes due to an internal error, it may do so before it has a chance to execute even a single instruction. Also, if the operating system sends a SIGKILL signal (kill -9 in Unix/Linux) or TerminateProcess (Windows) signal, the programme must stop immediately without waiting for cleaning. In addition to the foregoing, the Runtime.halt() function may be used to stop the JVM without allowing the shutdown hooks to run.


Shutdown hooks are invoked when an application exits normally (all threads have finished or System.exit(0) has been called). When the JVM is closing down due to external factors like a user asking a termination (Ctrl+C), an O/S issuing a SIGTERM (standard kill command, without -9), or the operating system is shutting down.

 

2. Shutdown Hooks can be forced to stop before they finish if they are initiated.
This is actually a variant of the previous scenario. Although the hook begins to run, it may be halted before it completes, for example, due to operating system shutdowns. Once the SIGTERM is issued, the operating system waits for a process to terminate for a set length of time. If the process does not end within this time limit, the operating system (OS) will forcefully terminate it by generating a SIGTERM signal (or the counterparts in Windows). As a result, it's possible that this occurs midway through the shutdown hook's execution.

Using a shutdown hook looks to be straightforward on the surface. We'll have to make a class that extends the java.lang package. Put the logic we want to perform when the VM goes down in the public void run() method of the Thread class. Then, using, we register a VM shutdown hook with an instance of this class.
 

3. We can have many Shutdown Hooks, but the sequence in which they are executed is not guaranteed.
As you might have guessed from the method name addShutdownHook, you can register multiple shutdown hooks (rather than setShutdownHook). The JVM, on the other hand, does not guarantee the order in which these hooks are performed. Shutdown hooks can be executed by the JVM in any order. Additionally, the JVM has the ability to run all of these hooks at the same time.
 

4. Shutdown Hooks cannot be registered or unregistered within Shutdown Hooks.
It is not possible to add new shutdown hooks or remove existing shutdown hooks once the JVM has started the shutdown procedure. The JVM will issue an IllegalStateException if this is tried.
 

5. Runtime.halt() is the only way to terminate the shutdown procedure once it has started.
Only Runtime.halt() (which violently kills the JVM) can stop the shutdown sequence from running once it has started (except for external influences such as SIGKILL). As a result, using System.exit() from within a Shutdown Hook will fail. In fact, using System.exit() from within a Shutdown Hook may cause the VM to become stuck, and we may have to aggressively kill the process.
 

6. Security permissions are required to use shutdown hooks.
If we're using Java Security Managers, the code that adds/removes shutdown hooks must have the shutdown hooks permission enabled at runtime. This function will throw a SecurityException if it is called without authorization in a secure environment.

Also see, Hashcode Method in Java

Frequently Asked Questions

  1. How does shutdown hook work?
    The addShutdownHook(Thread hook) function creates a new shutdown hook for a virtual machine. There are two types of events that cause the Java virtual machine to shut down. A user interrupt, such as ctrl + C, or a system-wide event, such as user logoff or system shutdown, causes the virtual machine to be terminated.
     
  2. How do I shut down Executorservice gracefully?
    When utilising an Executor, we may use the shutdown() and shutdownNow() methods to shut it down. It will not, however, wait until all threads have completed their execution.
    The awaitTermination() function can be used to wait for existing threads to finish their execution.
     
  3. How do you stop spring boot gracefully?
    Use the static exit() method in the SpringApplication class to gracefully quit your Spring Boot application. To ensure that the ApplicationContext is gently terminated on exit, SpringApplication registers a shutdown hook with the JVM implicitly.

Conclusion

We hope that this blog has helped you understand more about shutdown hooks in Java, and if you want to learn more, check out our Introduction to Java articles.

Head over to our practice platform Coding Ninjas Studio to practise top problems, attempt mock tests, read interview experiences, and much more. Please upvote our blog to assist other ninjas in their development.

Happy Learning!

Live masterclass