I have a class that uses a static initialization block to set up a connection to a database. The class has many public static methods that query the db. I would like to properly close this connection in a static block that executes just before the program terminates, kind of like a finally block in a try/catch. I am almost certain that something like this does not exist in Java. Is my best option to open and close the connection with each query?
Have a look at this : Running a method when closing the program?
You could try writing the code to close connection in this method.
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
//code to close connection
}
}, "Shutdown-thread"));
}
Opening and closing the connection for every query will cause an additional overhead on system making the application slow.
You could surround the final query of your DB program with try catch blocks instead and release the connection in the finally clause (for the last query of your program).
NOTE: If the JVM terminates before the main thread finishes execution, i.e. System.exit() executes, the subsequent code and the finally block won't be executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With