Is a Java DB-Connection closed automatically on System.exit() or if the program terminates (end of main method)?
CodePudding user response:
If you use System.exit
your application terminates abruptly. Which means it is unlikely there is only coordinated cleanup. Same goes for ending an application without explicitly closing connections. As Gyro Gearless points out in the comments, registered shutdown hooks are run, as are finalizers if finalization on exit is enabled, but neither applies in general for database connections (though specific implementations of a driver or data source might register a shutdown hook or implement a finalizer, this is not a general rule).
When the application ends, socket connections will likely be closed abruptly, which will eventually get noticed by the database server. For correctness (e.g. is data committed or rolled back, etc), and timeliness of releasing database resources like locks, etc, it is better to explicitly handle closing connections (e.g. using try-with-resources, and closing connections before calling System.exit
).
BTW, it is a common misunderstanding that Java applications end when the main
method ends. That is not how it works. A Java applications ends when the last non-daemon thread ends. In a very basic application that might be shortly after the main
method ends, but that is just a side-effect of not having any other non-daemon threads running.
CodePudding user response:
Most of the time, getConnection() will simply get a connection from a pool of connections, that stay open for a very long time. If you don't close() the connection, it will not be put back into the pool of available connections, and after a few seconds or minutes, you won't have any connection available anymore.
The title asks about System.exit(). If you call System.exit(), then the connection will end up being closed because the database will notice that the communication is broken. But it's extremely rare for a program to startup, execute a query, and exit. Most of the applications start and stay running for days or even months.
If getConnection() creates a new Connection, then the only thing that will happen at the end of the method is that the Connection could be garbage collected. But the GC won't call the close() method for you. And, anyway, you want to close as soon as possible.