Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for threads to write changes in the shutdownhook

I Have a shutdownhook, that is executed when the process is terminated. However the changes that the program makes to the h2 database are not persistent. Only if I let the shutdown thread wait some time after the commit, I will see the changes in the DB when I strat up again.

Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
        // H2 db add row, commit and close
        Thread.sleep(1000); // in try/catch
        System.out.println("Shutdown complete");
    }
}

Only with a sleep, I will see the changes next time I connect to the DB.

Does anybody know how to wait for the H2 database to finish the operation before the process terminated? I want to avoid a Thread.sleep() with a random time...

like image 799
morja Avatar asked Dec 15 '11 09:12

morja


1 Answers

You can use the SHUTDOWN command in order to properly flush all writes to disk before closing your application.

An alternative solution would be to call CHECKPOINT SYNC in your shutdown hook (but before closing all connections). This would not "close" the database which should be done automatically anyway when the last connection is closed.

like image 89
a_horse_with_no_name Avatar answered Oct 07 '22 09:10

a_horse_with_no_name