Breaking News
Home / Java / Java Tutorials / Understanding Java Shutdown Hook

Understanding Java Shutdown Hook

JVM Shutdown Hook SnippetThe JVM provides the capability to add Shutdown hooks at Runtime. This shutdown hooks can be used to perform any resource cleanup or save state as required just before the JVM shuts down either normally or abruptly.

There can be more than one shutdown hooks that can be registered any time when the JVM is running via Runtime API. This hook is implemented as a Java Thread. The thread has the run() method which will get executed when the hook is executed by JVM at shutdown.

Java Shutdown Hook Example

The following example shows how to use the Java Shutdown Hook.

package com.livrona.snippets.system;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * This snippet shows how to writer and register the shutdown hook with the VM.
 * 
 * @author java4learners
 * 
 */
public class ShutdownHookExample {

	/**
	 * Main method
	 * @param args
	 * @throws Exception
	 */
	public static final void main(String args[]) throws Exception {

		File file = new File("test.dat");
		// open the file writer
		final FileWriter fileWriter = new FileWriter(file);

		// Add the shutdown hook as new java thread to the runtime.
		// can be added as inner class or a separate class that implements
		// Runnable or extends Thread
		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				System.out.println("in : run () : shutdownHook");

				// save state, resource clean,up etc.
				if (fileWriter != null) {
					try {
						// try to close the open file
						fileWriter.flush();
						fileWriter.close();
						System.out.println("File closed successfully");
					} catch (IOException e) {
						System.out.println("Failed to flush/close the file :"
								+ e.getMessage());
						e.printStackTrace();
					}
				}
				System.out.println("Shutdown hook completed...");
			}
		});

		// main sample code, open file and write, then throw dummy Exception
		// once the JVM terminates, the shutdown hook, would close the file.

		for (int i = 0; i < 10; i++) {
			fileWriter.write("Line : " + i);
		}
		throw new RuntimeException("Dummy Exception to cause JVM to exit");
	}
}

 [pb_builder]

Check Also

Have a Question

How to select a JVM Analyzing Tool?

A JVM monitoring tool also know as a Diagnostic might be needed to fine tune …

Leave a Reply