0

As you all know H2 is a powerful pure Java DBMS with several features like server/client mode and embedded
When working on a little software with a H2 database ,I ran into a problem :
the software crashes and the connection remains open ,when restarting the software I cannot access the database again (It's in embedded mode so it's locked) and to bypass this problem I had to shutdown Java virtual machine manually using task manager
Is there a way in case such an event happens (application crash) and yet I can restore the connection normally ?

3 Answers3

0

I have strong suspicion your program suffer from poor code failing to close connection on exception. Review all your database code and make sure all connection are closed even when exception is thrown.

A common approach is to close the connection on the finally block of try-catch-finally.

gerrytan
  • 40,313
  • 9
  • 84
  • 99
  • You can't just go out there in the code and try catch or try finally everything, because you can never protect every bit of your code of crashing –  Nov 20 '13 at 08:50
0

When the JVM exists normally, H2 normally closes the database itself, if you haven't done it yourself explicitly.

In worst case scenarios, you might be able to use Thread#setDefaultUncaughtExceptionHandler to terminate the JVM safely and/or close the database

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • This looks a good solution I will give it a try. By the way I know it's a very odd case but this (app crashing DB not closing) happened to me more than once –  Nov 20 '13 at 08:51
  • If the JVM is still running, then you've only "crashed" the application, making it unstable. You may need to play around with this to get it right, as I've found that sometimes it doesn't always work – MadProgrammer Nov 20 '13 at 08:54
  • If it helped solve your issue, you can always accept the answer - the little "ghost" tick next to the answer ;) – MadProgrammer Nov 22 '13 at 01:09
0

@Ossama Nasser: yes, you can trap everything. And you better do it, or know in advance which exceptions you decide to let terminate your program, and what effect there will be on your programs resources.

Unix-C programs use setjmp() & longjmp(). It is primitive, but it is effective for most signals.

However, the JVM offers an alternative to the approach of "put a try/finally around everything in main()":

Runtime.getRuntime().addShutdownHook(new <whatever you write as a handler class>)
  • FYI- H2 already uses a `ShutdownHook` to manage this type of connections. So long as the JVM shuts down in a normal manner ;) – MadProgrammer Nov 25 '13 at 23:31