Using JVM shutdown hooks is easy; first define a class that extends the Thread class:
class MyShutdown extends Thread {Here I am assuming that my JDBC access utilities are in a class DbUtil that has a static method close_connections() for sending HSQLDB a "SHUDOWN COMPACT" command.
public MyShutdown() { super(); }
public void run() {
System.out.println("\n\n*** MyShutDown thread started ***\n");
try {
DbUtil.close_connections();
} catch (Exception ee) { ee.printStackTrace(); }
}
}
Registering a JVM shutdown hook is also easy:
MyShutdown sh = new MyShutdown();Make sure you only register the shutdown hook exactly one time.
Runtime.getRuntime().addShutdownHook(sh);
When the JVM that is running my application terminates, my shutdown hook is called. This works well for both running unit tests and when used inside a Tomcat container.
I use JVM shutdown hooks fairly often - it is useful to be able to perform cleanup work as a JVM terminates. On Linux servers, be sure to shutdown Tomcat (or JBoss, etc.) cleanly. Shutdown hooks are obviously not called if there is a server crash.