Shutdown Hook Tutorial

Have you ever felt the need to clean up things, to close a log file, to send some alert, or take some other action when the Java Virtual Machine is shutting down?

You can do such things only if the user closes your application the way you intended it. But what if someone presses CTRL+C and shutdown the VM, or sends a kill signal in Unix/Linux?

Will your memory-buffered logfile not be written to disk, with the loss of important information as a consequence?

The only way to make some code execute right before the VM shuts down is using shutdown hooks. And that’s exactly what this article will teach you.

The way it works
Allthough not known by many Java developers, all magic resides in the java.lang.Runtime class since the Java 1.3.
If you have a look at the API docs, you’ll find a method named addShutdownHook, which takes a Thread object as it’s single parameter.

What this method does is registering the Thread to be started right before the VM shuts down.

There is also a method named removeShutdownHook, which also takes the reference to the Thread object as a parameter. This method allows you to remove a Thread from the list of threads to be started by the VM before it closes.

Multiple Shutdown Hook threads
Now, what happens if you add multiple threads as a shutdown hook? Well, quite simple: all threads are started before the VM shuts down, which allows all code in the threads to execute.

However, one important thing to keep in mind is that there is no particular order in which the threads will run. They’ll all come eligible to get CPU time before the VM shuts down, and this shutdown is delayed until the last thread stops, but if you need to synchronize multiple thread’s workings, you’ll have to do it yourself (just as with normal thread usage).

The next example source class demonstrates the use of shutdown hooks: (compile it, run it, and shutdown the VM any way you can, the shutdown hook thread should get executed!)

Sample source

public class ShutdownDemo {

public ShutdownDemo ( ) {

Thread t = new ShutdownHookThread ( “Here I am !!!” );

Runtime.getRuntime().addShutdownHook ( t );

System.out.println ( “Now shut me down …” );

while ( true ) {
System.out.print ( “.” );
try {
Thread.sleep ( 300 );
} catch ( InterruptedException ie ) { }


public static void main ( String args[] ) {
new ShutdownDemo ( );


class ShutdownHookThread extends Thread {

protected String message;

public ShutdownHookThread ( String message ) {
this.message = message;

public void run ( ) {
System.out.println ( );
System.out.println ( message );


by G?nther