Reputation: 19766
In JDBC literatur I often encounter snippets like
void databaseCall() {
Connection con = null;
Statement statement = null
try {
con = getConnection(...);
statement = con.createStatement(...);
// do some query
} catch (SQLException e) {
// bla bla
} finally {
try {con.close();} catch (Exception e1) {}
try {statement.close();} catch (Exception e1) {}
}
}
I know it's best practice to close connections and statements explicity, but, in this case, apparently the resources con
and statement
will be closed when the method is finished, i.e., when the try
block is finished. Is the close
statements in the finally
block really necessary? Even if we did not release the resources explicitly, wouldn't they be closed any way when the method is finished?
Upvotes: 1
Views: 4646
Reputation: 1
Suppose you have brought 20 connection for ekart application.That means connection pool has only 20 connections.If you send request to server, pool provides a connection for every request.If you wont close the connection, after 20th request you gets 'OutOfConnectionError',even you cannt handle this error and you cannot send request , because there is no connections.If you close the conncetion then only you can send new request.........
Upvotes: -2
Reputation: 691695
No, they wouldn't be closed.
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.
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()
, but the question body doesn't. 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. So you really want to release the connection once you have finished using it.
Upvotes: 5