Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static finally block in Java

Tags:

java

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?

like image 393
Justin Avatar asked Nov 28 '25 23:11

Justin


2 Answers

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"));
}
like image 197
Ridhima Avatar answered Dec 01 '25 14:12

Ridhima


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.

like image 45
Adithya Upadhya Avatar answered Dec 01 '25 12:12

Adithya Upadhya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!