Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I close a connection that came from a datasource?

When I do a dataSource.getConnection(), when I want the connection to be return to the pool (and not closed), does calling the close method return the connection to the pool or actually close it?

like image 666
Guillaume Coté Avatar asked Jan 12 '11 15:01

Guillaume Coté


People also ask

Do we need to close DataSource connection?

So when your program starts up you open such a connection, and once the whole program no longer needs the connection (often shortly before terminating) you close it. public static void main(String[] args) { DataSource dataSource = createDataSource(); try (Connection connection = dataSource.

What happens if you don't close a database connection?

If you don't close it, it leaks, and ties up server resources. @EJP The connection itself might be thread-safe (required by JDBC), but the applications use of the connection is probably not threadsafe. Think of things like different transaction isolation, boundaries (commit/rollback/autocommit) etc.

Should I close DB connection after query?

For the purpose of safe coding, you should always close database connections explicitly to make sure that the code was able to close itself gracefully and to prevent any other objects from reusing the same connection after you are done with it.

Should I close a pooled DB connection?

Yes, certainly you need to close the pooled connection as well. It's actually a wrapper around the actual connection. It wil under the covers release the actual connection back to the pool.


1 Answers

When you call the close() on connection returned by a DataSource, it would return that to the pool to be used by other thread. Closing the connection defeats the purpose of the pool.

like image 116
Aravind Yarram Avatar answered Sep 25 '22 08:09

Aravind Yarram