Tips on Shutdown Hook

These tips are about how to make some code execute closing of a log file, cleaning up things, to sending alerts or something else - right before the Java Virtual Machine shuts down.

Shutdown hooks are the right tools to do these things, which otherwise can be executed only in case the user closes the application the proper way, and not by pressing CTRL+C or sending a kill signal in Unix/Linux, which brings forth every chance that the memory-buffered logfile will not be written to disk without losses of important information. In such a case, when applying shutdown hooks, you should be aware of the fact (a lot of Java developers are ignorant about) that starting from Java 1.3 all magic resides with the java.land.runtime. Going through the API docs you’ll come across the addShutdownHook method, which takes  a Thread object as its only parameter and registers this Thread to be started immediately prior to the VM’s shutting down.

The other method, named removeShutdownHook, that takes as a parameter the reference to the Thread object as well, allows to remove the Tread from the list threads that have been added for being started by the VM prior to its closing.

And what happens if multiple threads have been added for Shutdown Hook? All of them simply get started right before the VM’s shutting down, with all code in these threads being executed. Yet the one essential thing to remember about multiple threads is that there will be no definite order in which they run. They all are subject and suitable for getting SPU time prior to the VM’s shutting down. And actually they delay the final shut down until the last thread is run and stops. Yet the working of multiple threads may be synchronized the same way as in case of a normal thread usage.

The following example source class will demonstrate the entire work of shutdown hooks, their compilation and execution no matter in what manner the VM is shut down:
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 );