Java Shutdown Hook Sample Code

If your Java application runs as a daemon process or continually runs in the background, there may be a need to recognize when it stops running.You may want to perform a few tasks before the process is completely gone.

The Java Runtime class allows you to add a shutdown hook to the process. The Java Virtual Machine (JVM) will shutdown a process when it finishes all tasks or when a user issues some sort of a kill command on the process.

When the JVM begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. The tutorial below gives an example of how to add or register your own shutdown hook.


Create Shutdown Hook Class

This sample Java class will first get the Runtime object using getRuntime() method. The next step is to call addShutdownHook() method and pass in an inline Thread. The contents of Thread eventually call our custom Cleanup class.

//Class to attach our custom shutdown hook to process
class RuntimeShutdownHook 
{

	public void attachShutDownHook() 
	{
		
		  //All classes or methods inside run() will be called before exiting
		  Runtime.getRuntime().addShutdownHook(new Thread() 
		  {
		   
			  @Override
			  public void run() 
			  {
				  System.out.println("Do Some housekeeing activities before Shutting Down.");
				  
				  //Call our custom cleanup class
				  Cleanup cleanup = new Cleanup();
			  }
			  
		  });

	}
}


Create Cleanup Class

We have created a new class called Cleanup. This class is responsible to perform any housekeeping or cleanup activities that we want run before our Java process exits. I have included a few sample methods that execute various tasks.

//Class that will perform various activities before shutdown
class Cleanup
{
	public Cleanup()
	{
		System.out.println("Start the Cleanup Process.");
		
		saveInternalData();
		
		cleanupSocket();
		
		cleanupStreams();
		
	}
	
	//Cleanup method 1
	public void saveInternalData()
	{
		System.out.println("Write out internal data to file.");
	}
	
	//Cleanup method 2
	public void cleanupSocket()
	{
		System.out.println("Close all open sockets.");
	}
	
	//Cleanup method 3
	public void cleanupStreams()
	{
		System.out.println("Close all open streams.");
	}
	
}


Java Shutdown Hook Sample Code

Let’s put all of the classes together in the complete sample code below that implements a Java Shutdown Hook that can be registered with the Runtime process.

package com.jcd.java.tutorials.MavenProject;

public class JavaShutdownHook
{

	public static void main(String[] args)
	{
		//Create our shutdown hook and attach it to Runtime
		RuntimeShutdownHook shutDownHook = new RuntimeShutdownHook();
		shutDownHook.attachShutDownHook();
		
		//Let's sleep for a minute to show the process
		try 
		{
			System.out.println("Let's sleep for a 1 minute.");
			Thread.sleep(60000);
			System.out.println("Ok done sleeping.");
		}
		catch(Exception ex) 
		{
			System.out.println(ex.toString());
		}
	}

}

//Class to attach our custom shutdown hook to process
class RuntimeShutdownHook 
{

	public void attachShutDownHook() 
	{
		
		  //All classes or methods inside run() will be called before exiting
		  Runtime.getRuntime().addShutdownHook(new Thread() 
		  {
		   
			  @Override
			  public void run() 
			  {
				  System.out.println("Do Some housekeeing activities before Shutting Down.");
				  
				  //Call our custom cleanup class
				  Cleanup cleanup = new Cleanup();
			  }
			  
		  });

	}
}

//Class that will perform various activities before shutdown
class Cleanup
{
	public Cleanup()
	{
		System.out.println("Start the Cleanup Process.");
		
		saveInternalData();
		
		cleanupSocket();
		
		cleanupStreams();
		
	}
	
	//Cleanup method 1
	public void saveInternalData()
	{
		System.out.println("Write out internal data to file.");
	}
	
	//Cleanup method 2
	public void cleanupSocket()
	{
		System.out.println("Close all open sockets.");
	}
	
	//Cleanup method 3
	public void cleanupStreams()
	{
		System.out.println("Close all open streams.");
	}
	
}
Let's sleep for a 1 minute.
Ok done sleeping.
Do Some housekeeing activities before Shutting Down.
Start the Cleanup Process.
Write out internal data to file.
Close all open sockets.
Close all open streams.


I hope you enjoyed this tutorial on creating your shutdown hook that can be easily added to your Java application. Depending on what your Java program does, you will need to edit the tasks that are called before the process exits the JVM.



Java References:

Add a Comment

Your email address will not be published. Required fields are marked *