Java.Servlet.Should i close connection in my code if i use connection pool ?

Short and clear answer:
YES, you absolutely must close the Connection yourself even when using a connection pool!

BUT — and this is very important —

  • Closing a connection from the pool does NOT physically close it to the database.
  • It just returns the connection back to the pool, making it available for reuse by other parts of your application.

🌟 Let’s explain carefully:

ActionWhat happens
Connection conn = dataSource.getConnection();You borrow a connection from the pool.
conn.close();You return the connection back to the pool.
Pool internallyKeeps connection alive to reuse. No real database disconnection.

If you don’t close:

  • The connection remains marked as “in use”.
  • Pool cannot reuse it.
  • Eventually, pool runs out of available connections → your app freezes or throws SQLException: Timeout waiting for connection from pool.

Therefore: Always close the connection when you are done!

Best way: use try-with-resources so it automatically closes, even if an exception happens:

Example:

DataSource ds = (DataSource) getServletContext().getAttribute("DataSource");

try (Connection conn = ds.getConnection();
     PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users");
     ResultSet rs = stmt.executeQuery()) {

    while (rs.next()) {
        String username = rs.getString("username");
        // do something
    }
    
} catch (SQLException e) {
    // log exception
    e.printStackTrace();
}
// No need to manually close conn, stmt, rs — done automatically!

Without try-with-resources: If you don’t use try-with-resources, then manually close everything inside finally block:

Connection conn = null;
try {
    conn = ds.getConnection();
    // work with conn
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

🚨 What happens if you forget to close connections?

  • Database pool starvation.
  • Your app may seem slow, stuck, or crash under load.
  • Pool throws errors like:
java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available

Database may block or refuse new connections.

✅ Final Short Rules:

ThingRule
Got connection from pool?Always close it!
Closing connectionReturns it to pool, not to DB
Best practiceUse try-with-resources

🔥 Real-life analogy:

Imagine a library (connection pool):

  • You borrow a book (connection).
  • You read it (query the DB).
  • You must return it to the shelf (pool) when done, so others can use it.
  • If you keep holding the book forever → no one else can read it!

Would you like me also to show a small demo project where:

  • one servlet forgets to close the connection,
  • and another servlet properly closes it,
    so you can feel the difference by seeing the errors appear? 🚀
This entry was posted in Без рубрики. Bookmark the permalink.