Home >Database >Mysql Tutorial >Should I Close Pooled JDBC Connections?

Should I Close Pooled JDBC Connections?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-03 22:19:14946browse

Should I Close Pooled JDBC Connections?

Closing JDBC Connections in Pool

Question: Should JDBC connections be closed when using a connection pool? If so, doesn't it defeat the purpose of pooling?

Answer: Yes, pooled connections should be closed. Closing a pooled connection releases the underlying connection back to the pool.

The connection pool keeps track of which connections are in use and which are free. When a connection is closed, the pool recognizes it as available for reuse.

Question: Is the following method suitable for obtaining a connection from the pool or the DriverManager?

public Connection getConnection(boolean pooledConnection) throws SQLException {
    if (pooledConnection) {
        if (ds == null) {
            try {
                ds = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/NamedInTomcat");
                return ds.getConnection();
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }
        return (ds == null) ? getConnection(false) : ds.getConnection();
    }
    return DriverManager.getConnection("jdbc:mysql://..." + dbName, uName, pWord);
}

Answer: The code is not recommended. The DataSource should be initialized once during application startup instead of in the method. Additionally, synchronization and null checks are unnecessary. The method should simply look up the DataSource once and return connections from it consistently.

Additional Considerations:

  • Always close JDBC resources in reversed order in a try-with-resources statement or in the finally block.
  • Avoid using DriverManager to establish connections manually if you're using a connection pool.

The above is the detailed content of Should I Close Pooled JDBC Connections?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn