Friday, August 19, 2005

OK, HSQLDB is cool after all

I complained a week ago about stability problems when using HSQLDB as an embedded database engine. By using a JVM shutdown hook, I totally solved my file locking problems.

Using JVM shutdown hooks is easy; first define a class that extends the Thread class:
class MyShutdown extends Thread {
public MyShutdown() { super(); }
public void run() {
System.out.println("\n\n*** MyShutDown thread started ***\n");
try {
DbUtil.close_connections();
} catch (Exception ee) { ee.printStackTrace(); }
}
}
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.

Registering a JVM shutdown hook is also easy:
   MyShutdown sh = new MyShutdown();
Runtime.getRuntime().addShutdownHook(sh);
Make sure you only register the shutdown hook exactly one time.
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.

1 comment:

Anonymous said...

Thanks, googled for this for a while.