A project that I was helping with recently required the ability to detect the shut down of Java Virtual Machine (JVM). I'm mainly a web developer so typically I generally don't care that much about the shut down of the virtual machine I'm more interested in the shut down of the context which can be detected by a ServletContextListener. In this case however the application was stand alone and didn't have a front end. In fact the only communication with the application was over raw sockets. The application would receive a shut down command and stop gracefully. The problem was that we also needed to be able to shut it down without having to fire up another process to send it this shut down command. Also during development it would sometimes fail to respond and need killing - in this situation we really needed the code to release resources it held.

The solution is a little known feature of the language that lets you register JVM shut down hooks. A shut down hook is simply a Thread that is registered with the JVM and run just before the JVM shuts down. The application below shows the basic idea with a trivial example. Obviously you could make the Hook thread arbitrarily complex and typically you would want it to hold references to other objects so that it can perform some sort of clean up on them.

One method that could be used to aid clean up is to define an interface that could be implemented by any object that requires resources to be freed at shut down. This interface would define a method such as freeResources() that could be called by the shut down hook.

package example;

public class ShutdownHook {

@param args
public static void main(String[] args) {
Hook hook = new Hook();
( "Running Main Application..." );
().addShutdownHook( hook );
( "Exiting." );

private static class Hook extends Thread {
public void run() {
System.out.println( "Running Clean Up..." );