Connection Pool

Basic Java
≈ 2 min read

Creating a physical connection for every request is expensive

Opening a database connection involves network communication, authentication, and session setup. If a server application creates a new physical connection for every HTTP request, it spends a lot of time on setup and quickly runs into the database connection limit.

A connection pool keeps a limited set of open connections in advance and lends them to the application for a short time. When code calls close() on a connection obtained from a pool, it usually does not close the physical database connection; instead, a logical wrapper returns the resource to the pool.

The application usually works through DataSource

try (Connection connection = dataSource.getConnection()) {
    try (PreparedStatement statement = connection.prepareStatement(
            "SELECT name FROM users WHERE id = ?")) {
        statement.setLong(1, 42);
        // execute query
    }
}

The DataSource interface gives the application a place to obtain connections. The interface itself does not have to represent a pool: a particular implementation may provide ordinary connections or may be backed by pooling infrastructure. In a typical server application, the details of creating and reusing connections are hidden behind a configured DataSource.

Pool size is a limit, not a way to open infinitely many connections

If every connection is busy, the next request must wait for a resource to be released or fail after a timeout. That is why leaking even one Connection is especially unpleasant in a pooled application: over time, fewer connections remain available.

Close Connection even when using a pool. The close() call tells the pool that the work is finished and the connection can be given to the next request. try-with-resources remains the right way to manage this lifecycle.