Java Connection Pooling with HikariCP
Java connection pooling keeps a small set of database connections open and lends them to your code whenever it needs one. Opening a fresh JDBC connection means a network handshake, a login and session setup, which often takes tens of milliseconds. A pool pays that cost once and then reuses the same connections thousands of times.
Every serious Java backend, from a small REST API to Spring Boot itself, talks to its database through a pool. In this lesson you will see how a pool works by building a tiny one, then use HikariCP, the most widely used Java connection pool, to configure pool size and timeouts, handle an exhausted pool, detect leaked connections, share a pool across threads, and wire a pool into a repository class.
How a Connection Pool Works
Without a pool, every request opens and closes its own physical connection. With a pool, connections are opened up front and recycled.
Without a pool: request -> open connection (slow) -> SQL -> close connection (every time)
With a pool: request -> borrow from pool (fast) -> SQL -> return to pool
pool -> keeps N physical connections open and healthy
DriverManager.getConnection() | Connection pool (DataSource) | |
|---|---|---|
| Cost per call | Full login every time | Usually microseconds |
What close() does | Closes the physical connection | Returns the connection to the pool |
| Limit on connections | None, so the database can be overloaded | Fixed maximum (for example 10) |
| Health checks | None | Validates, replaces and retires connections |
Note: Your code still calls
getConnection()andclose()exactly as in the Java Database Connection lesson. The difference is that it gets them from ajavax.sql.DataSourcebacked by a pool instead of fromDriverManager.
Building a Tiny Connection Pool to See the Idea
A pool is basically a thread-safe queue of open connections. Borrowing takes one from the queue; returning puts it back. This small version uses ArrayBlockingQueue, which makes a borrower wait when the queue is empty.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class SimplePoolDemo {
static class SimpleConnectionPool {
private final BlockingQueue<Connection> idleConnections;
SimpleConnectionPool(String url, int size) throws SQLException {
idleConnections = new ArrayBlockingQueue<>(size);
for (int i = 0; i < size; i++) {
idleConnections.add(DriverManager.getConnection(url, "sa", "")); // open once
}
}
Connection borrow() throws InterruptedException {
return idleConnections.take(); // waits if every connection is in use
}
void giveBack(Connection connection) {
idleConnections.offer(connection);
}
int available() {
return idleConnections.size();
}
}
public static void main(String[] args) throws Exception {
SimpleConnectionPool pool = new SimpleConnectionPool("jdbc:h2:mem:demo;DB_CLOSE_DELAY=-1", 2);
System.out.println("Available at start: " + pool.available());
Connection first = pool.borrow();
Connection second = pool.borrow();
System.out.println("Available after borrowing 2: " + pool.available());
pool.giveBack(first);
Connection third = pool.borrow();
System.out.println("Reused the same connection: " + (third == first));
pool.giveBack(second);
pool.giveBack(third);
System.out.println("Available at end: " + pool.available());
}
}
Output:
Available at start: 2
Available after borrowing 2: 0
Reused the same connection: true
Available at end: 2
How it works:
- The constructor opens two physical connections once and stores them in the queue.
borrow()removes a connection from the queue, so after two borrows nothing is left. A thirdborrow()would block until someone gives one back.- After
firstis returned, the next borrow gets that very same object. No new login happened.
This toy pool has real problems: it cannot tell if a connection has died, it never times out a waiting borrower, and if code forgets giveBack() the connection is lost forever. Production pools such as HikariCP solve all of these.
Adding HikariCP to Your Project
HikariCP is a small, fast pool used by default in Spring Boot. Add it together with your JDBC driver. The examples in this lesson use the in-memory H2 database so they run without a server.
<dependencies>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>7.1.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.3.232</version>
</dependency>
</dependencies>
For Gradle, the same dependencies are:
implementation("com.zaxxer:HikariCP:7.1.0")
implementation("com.h2database:h2:2.3.232")
How it works:
- HikariCP needs Java 11 or newer. Use the latest release shown on Maven Central.
- HikariCP logs through SLF4J. Without a logging backend you will see a one-time "No SLF4J providers were found" message. Add
org.slf4j:slf4j-simple(or Logback) if you want to see the pool's log lines.
Java Connection Pooling with HikariCP: First Example
You describe the pool with a HikariConfig, then create a HikariDataSource from it. The data source is the pool, and you borrow connections from it with getConnection().
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class HikariFirstPool {
public static void main(String[] args) throws SQLException {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:h2:mem:shop;DB_CLOSE_DELAY=-1");
config.setUsername("sa");
config.setPassword("");
config.setMaximumPoolSize(5);
config.setPoolName("ShopPool");
try (HikariDataSource dataSource = new HikariDataSource(config)) {
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.executeUpdate("CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(40), price DECIMAL(10,2))");
statement.executeUpdate("INSERT INTO products VALUES (1, 'Keyboard', 2499.00), (2, 'Mouse', 799.00)");
System.out.println("Connection class: " + connection.getClass().getSimpleName());
} // close() hands the connection back to the pool
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet rows = statement.executeQuery("SELECT name, price FROM products ORDER BY id")) {
while (rows.next()) {
System.out.println(rows.getString("name") + " - " + rows.getBigDecimal("price"));
}
}
System.out.println("Pool name: " + dataSource.getPoolName());
} // closing the data source shuts the whole pool down
}
}
Output:
Connection class: HikariProxyConnection
Keyboard - 2499.00
Mouse - 799.00
Pool name: ShopPool
How it works:
new HikariDataSource(config)starts the pool immediately and opens its first connection, so a wrong URL or password fails right here instead of on the first request.getConnection()returns aHikariProxyConnection, a thin wrapper around the real H2 connection. Itsclose()returns the real connection to the pool.HikariDataSourceisCloseable. Closing it at application shutdown closes every physical connection.DB_CLOSE_DELAY=-1keeps the H2 in-memory database alive between borrows. Real databases such as MySQL or PostgreSQL do not need it.
Borrowing and Returning: close() Does Not Really Close
Because close() only returns the connection, the next borrower gets the same physical connection inside a new proxy. You can watch this with a pool of size 1 and the unwrap() method, which exposes the driver's real connection object.
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.HikariPoolMXBean;
import org.h2.jdbc.JdbcConnection;
import java.sql.Connection;
import java.sql.SQLException;
public class BorrowAndReturn {
public static void main(String[] args) throws SQLException {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:h2:mem:reuse;DB_CLOSE_DELAY=-1");
config.setUsername("sa");
config.setMaximumPoolSize(1);
try (HikariDataSource dataSource = new HikariDataSource(config)) {
HikariPoolMXBean poolStats = dataSource.getHikariPoolMXBean();
Connection firstProxy = dataSource.getConnection();
JdbcConnection firstPhysical = firstProxy.unwrap(JdbcConnection.class);
System.out.println("Active while borrowed: " + poolStats.getActiveConnections());
firstProxy.close();
System.out.println("Active after close(): " + poolStats.getActiveConnections());
try (Connection secondProxy = dataSource.getConnection()) {
JdbcConnection secondPhysical = secondProxy.unwrap(JdbcConnection.class);
System.out.println("Same proxy object: " + (firstProxy == secondProxy));
System.out.println("Same physical connection: " + (firstPhysical == secondPhysical));
}
}
}
}
Output:
Active while borrowed: 1
Active after close(): 0
Same proxy object: false
Same physical connection: true
How it works:
getHikariPoolMXBean()gives live statistics: active (borrowed), idle, total and threads waiting.- Each borrow creates a fresh proxy, so an old proxy that was closed cannot accidentally be used again.
- The physical H2 connection behind both proxies is the same object. The expensive login happened only once.
Note: Always borrow with try-with-resources. A connection that is never closed is never returned, and after
maximumPoolSizesuch leaks the pool is empty and every request starts timing out.
Important HikariCP Configuration Settings
HikariCP works well with its defaults; most applications only set the URL, credentials and pool size. All time values are in milliseconds.
| Setting | Default | What it controls |
|---|---|---|
maximumPoolSize | 10 | Most connections the pool will ever open |
minimumIdle | same as maximumPoolSize | Idle connections to keep ready (default means a fixed-size pool) |
connectionTimeout | 30000 | How long getConnection() waits before failing (minimum 250) |
idleTimeout | 600000 | How long an idle connection may sit unused (only when minimumIdle is lower than the maximum) |
maxLifetime | 1800000 | Maximum age of a connection before it is retired and replaced |
keepaliveTime | 120000 | How often idle connections are pinged to stop firewalls dropping them |
leakDetectionThreshold | 0 (off) | Log a warning if a connection is held longer than this |
poolName | HikariPool-1, HikariPool-2, ... | Name used in logs and monitoring |
You can also load the settings from a Properties object, which is how most applications read them from a file such as db.properties.
import com.zaxxer.hikari.HikariConfig;
import java.util.Properties;
public class HikariFromProperties {
public static void main(String[] args) {
Properties settings = new Properties();
settings.setProperty("jdbcUrl", "jdbc:h2:mem:school;DB_CLOSE_DELAY=-1");
settings.setProperty("username", "sa");
settings.setProperty("password", "");
settings.setProperty("maximumPoolSize", "8");
settings.setProperty("connectionTimeout", "5000");
settings.setProperty("maxLifetime", "900000");
settings.setProperty("poolName", "SchoolPool");
HikariConfig config = new HikariConfig(settings);
System.out.println("Pool name: " + config.getPoolName());
System.out.println("Max size: " + config.getMaximumPoolSize());
System.out.println("Wait limit: " + config.getConnectionTimeout() + " ms");
System.out.println("Max lifetime: " + config.getMaxLifetime() / 60000 + " minutes");
}
}
Output:
Pool name: SchoolPool
Max size: 8
Wait limit: 5000 ms
Max lifetime: 15 minutes
How it works:
- Each property name matches a
HikariConfigsetter without thesetprefix (maximumPoolSizemaps tosetMaximumPoolSize). new HikariConfig(properties)copies the values; nothing connects until you build aHikariDataSource.- Keep
maxLifetimea few minutes shorter than any connection time limit set by your database or network, so HikariCP retires connections before the server cuts them.
Note: Bigger is not better. A pool of 10 to 20 connections serves a surprising amount of traffic, because each query holds a connection only for milliseconds. HikariCP's own guide suggests starting near
(CPU cores x 2) + number of diskson the database server and measuring from there.
What Happens When the Pool Runs Out
When every connection is borrowed, getConnection() waits up to connectionTimeout. If none comes back in time, it throws SQLTransientConnectionException.
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLTransientConnectionException;
public class PoolExhausted {
public static void main(String[] args) throws SQLException {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:h2:mem:busy;DB_CLOSE_DELAY=-1");
config.setUsername("sa");
config.setMaximumPoolSize(2);
config.setConnectionTimeout(500); // wait at most half a second
try (HikariDataSource dataSource = new HikariDataSource(config)) {
Connection first = dataSource.getConnection();
Connection second = dataSource.getConnection();
System.out.println("Borrowed 2 of 2 connections");
long start = System.currentTimeMillis();
try (Connection third = dataSource.getConnection()) {
System.out.println("Got a third connection");
} catch (SQLTransientConnectionException e) {
long waited = System.currentTimeMillis() - start;
System.out.println("Gave up after waiting at least 500 ms: " + (waited >= 500));
System.out.println("Exception: " + e.getClass().getSimpleName());
}
first.close(); // return one connection
try (Connection retry = dataSource.getConnection()) {
System.out.println("Retry succeeded after a connection was returned");
}
second.close();
}
}
}
Output:
Borrowed 2 of 2 connections
Gave up after waiting at least 500 ms: true
Exception: SQLTransientConnectionException
Retry succeeded after a connection was returned
How it works:
- With both connections out, the third request waits 500 ms and then fails. The message (not printed here) includes the pool state, for example
total=2, active=2, idle=0. - "Transient" means the same request may succeed later, which is exactly what happens once
firstis returned. - In a web application this exception usually means either the pool is too small for the load, or some code is holding connections too long or leaking them.
Detecting Connection Leaks
A leak is a borrowed connection that is never closed. Set leakDetectionThreshold and HikariCP logs a warning, with the stack trace of the code that borrowed the connection, whenever a connection is held longer than that.
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class LeakDetection {
// Bug: borrows a connection and never closes it
static void leakyReport(HikariDataSource dataSource) throws SQLException {
Connection connection = dataSource.getConnection();
connection.createStatement().executeQuery("SELECT 1");
}
public static void main(String[] args) throws Exception {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:h2:mem:leaks;DB_CLOSE_DELAY=-1");
config.setUsername("sa");
config.setPoolName("ReportPool");
config.setLeakDetectionThreshold(2000); // warn after 2 seconds
try (HikariDataSource dataSource = new HikariDataSource(config)) {
leakyReport(dataSource);
Thread.sleep(3000); // give the leak detector time to fire
System.out.println("Active connections: " + dataSource.getHikariPoolMXBean().getActiveConnections());
}
}
}
Output (program output plus the SLF4J warning, shortened):
WARN com.zaxxer.hikari.pool.ProxyLeakTask - Connection leak detection triggered for conn0: url=jdbc:h2:mem:leaks user=SA on thread main, stack trace follows
java.lang.Exception: Apparent connection leak detected
at LeakDetection.leakyReport(LeakDetection.java:10)
...
Active connections: 1
How it works:
leakyReport()borrows a connection and returns without closing it, so the pool still counts it as active.- After 2 seconds HikariCP logs the warning. The stack trace points straight at the line that called
getConnection(), which is the line to fix. - The warning only appears if an SLF4J backend such as
slf4j-simpleis on the classpath. The exact wording of the log line can differ slightly between versions.
Note: Leak detection is a diagnostic tool, not a fix. Turn it on in development or temporarily in production while hunting a leak, then fix the code with try-with-resources.
Sharing One Pool Across Many Threads
A pool is thread-safe, and it naturally limits how many threads can use the database at once. Here twelve tasks run on six threads but share a pool of three connections. A counter records the most connections ever in use at the same moment.
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class PoolWithThreads {
static final AtomicInteger inUse = new AtomicInteger();
static final AtomicInteger peakInUse = new AtomicInteger();
static void saveOrder(HikariDataSource dataSource, int orderId) {
try (Connection connection = dataSource.getConnection();
PreparedStatement insert = connection.prepareStatement("INSERT INTO orders VALUES (?, ?)")) {
int current = inUse.incrementAndGet();
peakInUse.accumulateAndGet(current, Math::max);
insert.setInt(1, orderId);
insert.setString(2, Thread.currentThread().getName());
insert.executeUpdate();
Thread.sleep(100); // simulate a slower query
inUse.decrementAndGet();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws Exception {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:h2:mem:orders;DB_CLOSE_DELAY=-1");
config.setUsername("sa");
config.setMaximumPoolSize(3);
try (HikariDataSource dataSource = new HikariDataSource(config)) {
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.executeUpdate("CREATE TABLE orders (id INT PRIMARY KEY, worker VARCHAR(40))");
}
ExecutorService workers = Executors.newFixedThreadPool(6);
for (int orderId = 1; orderId <= 12; orderId++) {
int id = orderId;
workers.submit(() -> saveOrder(dataSource, id));
}
workers.shutdown();
workers.awaitTermination(30, TimeUnit.SECONDS);
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet count = statement.executeQuery("SELECT COUNT(*) FROM orders")) {
count.next();
System.out.println("Orders saved: " + count.getInt(1));
}
System.out.println("Peak connections in use: " + peakInUse.get());
System.out.println("Pool size limit: " + config.getMaximumPoolSize());
}
}
}
Output:
Orders saved: 12
Peak connections in use: 3
Pool size limit: 3
How it works:
- Six threads compete for three connections. Three threads work while the other three wait inside
getConnection(). - The peak never goes above 3, so the database never sees more than three sessions from this application, however many threads it runs.
- This is the same idea as a Java thread pool: a fixed number of shared, expensive resources serve many short tasks.
Real-World Example: A Shared DataSource for a Repository
In a real application there is exactly one pool per database, created at startup, shared by every repository, and closed at shutdown. Settings come from environment variables so the same code runs on a laptop and on a server.
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class ProductCatalogApp {
// Builds the single pool for the application
static HikariDataSource createDataSource() {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(envOrDefault("DB_URL", "jdbc:h2:mem:catalog;DB_CLOSE_DELAY=-1"));
config.setUsername(envOrDefault("DB_USER", "sa"));
config.setPassword(envOrDefault("DB_PASSWORD", ""));
config.setMaximumPoolSize(Integer.parseInt(envOrDefault("DB_POOL_SIZE", "10")));
config.setConnectionTimeout(5000);
config.setPoolName("CatalogPool");
return new HikariDataSource(config);
}
static String envOrDefault(String name, String fallback) {
String value = System.getenv(name);
return value == null || value.isBlank() ? fallback : value;
}
record Product(int id, String name, BigDecimal price) { }
// Depends only on the DataSource interface, not on HikariCP
static class ProductRepository {
private final DataSource dataSource;
ProductRepository(DataSource dataSource) {
this.dataSource = dataSource;
}
void createTable() throws SQLException {
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.executeUpdate("CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(40), price DECIMAL(10,2))");
}
}
void add(Product product) throws SQLException {
try (Connection connection = dataSource.getConnection();
PreparedStatement insert = connection.prepareStatement("INSERT INTO products VALUES (?, ?, ?)")) {
insert.setInt(1, product.id());
insert.setString(2, product.name());
insert.setBigDecimal(3, product.price());
insert.executeUpdate();
}
}
List<Product> findCheaperThan(BigDecimal limit) throws SQLException {
List<Product> results = new ArrayList<>();
try (Connection connection = dataSource.getConnection();
PreparedStatement query = connection.prepareStatement(
"SELECT id, name, price FROM products WHERE price < ? ORDER BY price")) {
query.setBigDecimal(1, limit);
try (ResultSet rows = query.executeQuery()) {
while (rows.next()) {
results.add(new Product(rows.getInt("id"), rows.getString("name"), rows.getBigDecimal("price")));
}
}
}
return results;
}
}
public static void main(String[] args) throws SQLException {
try (HikariDataSource dataSource = createDataSource()) {
ProductRepository products = new ProductRepository(dataSource);
products.createTable();
products.add(new Product(1, "Keyboard", new BigDecimal("2499.00")));
products.add(new Product(2, "Mouse", new BigDecimal("799.00")));
products.add(new Product(3, "USB Cable", new BigDecimal("199.00")));
products.add(new Product(4, "Monitor", new BigDecimal("12999.00")));
System.out.println("Products under 1000:");
for (Product product : products.findCheaperThan(new BigDecimal("1000"))) {
System.out.println(" " + product.name() + " - " + product.price());
}
System.out.println("Pool: " + dataSource.getPoolName()
+ ", active now: " + dataSource.getHikariPoolMXBean().getActiveConnections());
}
}
}
Output:
Products under 1000:
USB Cable - 199.00
Mouse - 799.00
Pool: CatalogPool, active now: 0
How it works:
- One pool for the whole app.
createDataSource()runs once inmain, and the try-with-resources block closes the pool when the program ends. - Configuration from the environment.
DB_URL,DB_USER,DB_PASSWORDandDB_POOL_SIZEoverride the defaults in production without changing code. Passwords never live in source files. - The repository only knows
DataSource.ProductRepositoryuses the standardjavax.sql.DataSourceinterface, so you could swap HikariCP for another pool, or for a test data source, without touching it. - Every method borrows and returns. Each method opens its connection with try-with-resources, uses it for one short unit of work, and returns it. That is why
active nowis0at the end: nothing leaked.
Note: If a method needs several statements in one transaction, borrow one connection and pass it to the steps, exactly as shown in Java JDBC Transactions. Borrowing a new connection for each step would put each step in a different transaction.
Pooled connections behave like the ones you used in Java JDBC Batch Update and the earlier JDBC lessons; only the way you get them changes. The next lesson moves one level higher, to JPA, where you work with Java objects and let a framework write the SQL.