Wait for threads to write changes in the shutdownhook
Asked Answered
O

2

6

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...

Override answered 15/12, 2011 at 9:56 Comment(0)
D
5

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.

Domino answered 15/12, 2011 at 10:3 Comment(0)
E
0

you can remove Thread.sleep() by using Executors, use its submit method to submit an instance of callable and then use ExecuterServcie -awaitTermination() method or you have an option to use is CountDownLatch -countDown() method. refer to CountDownLatch and ExecutorService

Eritrea answered 18/12, 2017 at 5:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.