// registering a shutdown hook to run when Apps terminates

Runtime.getRuntime().addShutdownHook( new Thread() {
    public void run() { database.close(); }
});