Skip to lesson

HikariCP setup and key settings

A hand-made pool cannot cope with many threads, broken connections and timeouts. ShopLite needs a proven pool library and a handful of settings that keep it fast and safe.

Adding HikariCP and creating a HikariDataSource

HikariCP is a small, fast connection pool library, and the one Spring Boot uses by default. You describe the pool in a HikariConfig and pass it to HikariDataSource, a DataSource with a pool behind it.

Example 1 adds HikariCP and a logging library to pom.xml. Example 2 creates the pool and borrows from it three times.

Example 1 · pom.xml

Runs in: a Maven project with the MySQL driver, HikariCP and the ShopLite database

XML
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>com.shoplite</groupId>    <artifactId>shoplite-console</artifactId>    <version>1.0-SNAPSHOT</version>    <properties>        <maven.compiler.release>17</maven.compiler.release>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>    </properties>    <dependencies>        <dependency>            <groupId>com.mysql</groupId>            <artifactId>mysql-connector-j</artifactId>            <version>26.7.0</version>            <scope>runtime</scope>        </dependency>        <dependency>            <groupId>com.zaxxer</groupId>            <artifactId>HikariCP</artifactId>            <version>7.1.0</version>        </dependency>        <dependency>            <groupId>org.slf4j</groupId>            <artifactId>slf4j-simple</artifactId>            <version>2.0.17</version>            <scope>runtime</scope>        </dependency>    </dependencies></project>
Output
[INFO] --- dependency:3.6.1:tree (default-cli) @ shoplite-console ---
[INFO] com.shoplite:shoplite-console:jar:1.0-SNAPSHOT
[INFO] +- com.mysql:mysql-connector-j:jar:26.7.0:runtime
[INFO] |  \- com.google.protobuf:protobuf-java:jar:4.31.1:runtime
[INFO] +- com.zaxxer:HikariCP:jar:7.1.0:compile
[INFO] |  \- org.slf4j:slf4j-api:jar:2.0.17:compile
[INFO] \- org.slf4j:slf4j-simple:jar:2.0.17:runtime

What this code does

  • The output is from mvn dependency:tree. HikariCP brings slf4j-api along by itself; SLF4J is the logging interface many Java libraries write their messages to.
  • slf4j-simple is a small SLF4J implementation that prints those messages to the console. Without it you get SLF4J(W): No SLF4J providers were found. and HikariCP stays silent, even about leaks.
  • The driver is back to runtime scope: from now on the code names only HikariCP classes and DataSource, never a MySQL class.

Example 2 · A first HikariCP pool: the same connection, borrowed three times

Runs in: a Maven project with the MySQL driver, HikariCP and the ShopLite database

HikariFirstPoolDemo.javaJava
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 HikariFirstPoolDemo {    static long connectionId(Connection con) throws SQLException {        try (Statement st = con.createStatement();             ResultSet rs = st.executeQuery("SELECT CONNECTION_ID()")) {            rs.next();            return rs.getLong(1);        }    }
    public static void main(String[] args) throws SQLException {        HikariConfig config = new HikariConfig();        config.setJdbcUrl(System.getenv("DB_URL"));        config.setUsername(System.getenv("DB_USER"));        config.setPassword(System.getenv("DB_PASSWORD"));        config.setMaximumPoolSize(3);
        try (HikariDataSource dataSource = new HikariDataSource(config)) {            for (int i = 1; i <= 3; i++) {                try (Connection con = dataSource.getConnection()) {                    System.out.println("Borrow " + i + ": server connection id " + connectionId(con)                            + " (" + con.getClass().getSimpleName() + ")");                }            }        }    }}
Sample output
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
[main] INFO com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Added connection com.mysql.cj.jdbc.ConnectionImpl@696da30b
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
Borrow 1: server connection id 7787 (HikariProxyConnection)
Borrow 2: server connection id 7787 (HikariProxyConnection)
Borrow 3: server connection id 7787 (HikariProxyConnection)
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown initiated...
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown completed.

What this code does

  • new HikariDataSource(config) starts the pool and opens the first connection at once (the Added connection line). If MySQL is down or the password is wrong, it fails right here, at startup.
  • All three borrows use server connection 7787, and the class is HikariProxyConnection: the wrapper whose close() gives the connection back. Compare this with MysqlDataSource in the previous lesson, which opened a new connection each time.
  • HikariDataSource is AutoCloseable, so try-with-resources shuts the pool down and closes the real connections at the end.

Add com.zaxxer:HikariCP (7.1.0 at the time of writing) and org.slf4j:slf4j-simple. HikariCP logs through SLF4J, and its warnings about leaks and timeouts are worth seeing.

Creating a HikariDataSource starts the pool, so do it once for the whole app and share it. A pool created per request is worse than no pool: every request then pays for a new pool and new connections.

Find the bug

Find the wrong line

Each snippet sets up HikariCP. Find the line that is wrong.

This DAO method looks up one product.

Round 1 of 2

maximumPoolSize and minimumIdle: sizing a small pool

maximumPoolSize is the most connections the pool holds, idle and active together (default 10). minimumIdle is how many idle connections it keeps ready (default: the same as maximumPoolSize, a fixed-size pool).

Example 3 starts a pool with minimumIdle 2 and a maximum of 5, and prints the total, active and idle connections at three moments.

Example 3 · Watching total, active and idle connections

Runs in: a Maven project with the MySQL driver, HikariCP and the ShopLite database

PoolSizeDemo.javaJava
import com.zaxxer.hikari.HikariConfig;import com.zaxxer.hikari.HikariDataSource;import com.zaxxer.hikari.HikariPoolMXBean;
import java.sql.Connection;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;
public class PoolSizeDemo {    static void show(String moment, HikariPoolMXBean pool) {        System.out.printf("%-26s total=%d active=%d idle=%d%n", moment,                pool.getTotalConnections(), pool.getActiveConnections(), pool.getIdleConnections());    }
    public static void main(String[] args) throws SQLException, InterruptedException {        HikariConfig config = new HikariConfig();        config.setJdbcUrl(System.getenv("DB_URL"));        config.setUsername(System.getenv("DB_USER"));        config.setPassword(System.getenv("DB_PASSWORD"));        config.setPoolName("shoplite-pool");        config.setMinimumIdle(2);        config.setMaximumPoolSize(5);
        try (HikariDataSource dataSource = new HikariDataSource(config)) {            HikariPoolMXBean pool = dataSource.getHikariPoolMXBean();            Thread.sleep(1000);                       // give the pool time to open its idle connections            show("After start:", pool);
            List<Connection> borrowed = new ArrayList<>();            for (int i = 0; i < 3; i++) {                borrowed.add(dataSource.getConnection());            }            show("Holding 3 connections:", pool);
            for (Connection con : borrowed) {                con.close();                          // back to the pool            }            Thread.sleep(1000);            show("After giving all back:", pool);        }    }}
Sample output
[main] INFO com.zaxxer.hikari.HikariDataSource - shoplite-pool - Starting...
[main] INFO com.zaxxer.hikari.pool.HikariPool - shoplite-pool - Added connection com.mysql.cj.jdbc.ConnectionImpl@696da30b
[main] INFO com.zaxxer.hikari.HikariDataSource - shoplite-pool - Start completed.
After start:               total=2 active=0 idle=2
Holding 3 connections:     total=3 active=3 idle=0
After giving all back:     total=3 active=0 idle=3
[main] INFO com.zaxxer.hikari.HikariDataSource - shoplite-pool - Shutdown initiated...
[main] INFO com.zaxxer.hikari.HikariDataSource - shoplite-pool - Shutdown completed.

What this code does

  • getHikariPoolMXBean() gives live pool numbers. Right after start the pool holds minimumIdle = 2 open, idle connections.
  • Borrowing 3 makes the pool open a third one (still below the maximum of 5). After all are given back, 3 stay open as idle connections. With minimumIdle below the maximum, the extra one is closed only after idleTimeout (10 minutes by default).
  • The pool opens connections in a background thread, which is why the program sleeps a little before printing.

Bigger is not faster. A database server can only run a few queries truly at the same time, roughly one per CPU core, so 100 connections mostly wait on each other. HikariCP's pool-sizing guide gives a starting point of (CPU cores × 2) + the number of disks of the database server; measure from there.

For ShopLite, a console app used by one person, 2 to 5 is plenty. A small web API often runs well with the default 10.

connectionTimeout, idleTimeout and maxLifetime

connectionTimeout is the longest getConnection() waits for a free connection before it throws, in milliseconds (default 30 000, at least 250).

Three timeouts control how long callers wait and how long connections live. The setters below use milliseconds.

Java
HikariConfig config = new HikariConfig();config.setJdbcUrl(System.getenv("DB_URL"));config.setUsername(System.getenv("DB_USER"));config.setPassword(System.getenv("DB_PASSWORD"));config.setPoolName("shoplite-pool");      // shows in every log lineconfig.setMaximumPoolSize(10);           // default 10config.setMinimumIdle(2);                // default: same as maximumPoolSizeconfig.setConnectionTimeout(5_000);      // wait for a free connection (default 30 000)config.setIdleTimeout(600_000);          // close extra idle connections (default)config.setMaxLifetime(1_800_000);        // replace connections after 30 min (default)HikariDataSource dataSource = new HikariDataSource(config);
  • connectionTimeout: lower it, for example to 5 000, so users get a quick error instead of a frozen screen.
  • idleTimeout: how long an extra idle connection, above minimumIdle, may sit unused before the pool closes it (default 600 000, 10 minutes). It does nothing for a fixed-size pool.
  • maxLifetime: the oldest a connection may get; the pool replaces it after this, never while it is in use (default 1 800 000, 30 minutes). Keep it a little shorter than any time limit on the database or network side. MySQL closes sessions idle longer than wait_timeout, 8 hours by default.

HikariCP also sends a light check to idle connections every keepaliveTime (default 2 minutes). Values below the minimums are corrected with a warning: maxLifetime is less than 30000ms, setting to default 1800000ms.

Fix the error

Fix the pool setting

Read the real HikariCP warning, then pick the line that fixes it.

Round 1 of 2

The pool starts, but it ignores the lifetime that was set.

config.setMaximumPoolSize(5);
config.setMaxLifetime(10_000);

Error

WARN com.zaxxer.hikari.HikariConfig - HikariPool-1 - maxLifetime is less than 30000ms, setting to default 1800000ms.

Pool exhausted and leakDetectionThreshold

A pool is exhausted when every connection is borrowed and none comes back within connectionTimeout. getConnection() then throws SQLTransientConnectionException: Connection is not available, request timed out.

Example 4 keeps two connections and asks for a third. Example 5 uses leakDetectionThreshold to find the line that borrowed too long.

Example 4 · Pool exhausted: Connection is not available, request timed out

Runs in: a Maven project with the MySQL driver, HikariCP and the ShopLite database

PoolExhaustedDemo.javaJava
import com.zaxxer.hikari.HikariConfig;import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;import java.sql.SQLException;
public class PoolExhaustedDemo {    public static void main(String[] args) throws SQLException {        HikariConfig config = new HikariConfig();        config.setJdbcUrl(System.getenv("DB_URL"));        config.setUsername(System.getenv("DB_USER"));        config.setPassword(System.getenv("DB_PASSWORD"));        config.setMaximumPoolSize(2);        config.setConnectionTimeout(1000);           // wait at most 1 second for a free connection
        try (HikariDataSource dataSource = new HikariDataSource(config)) {            Connection first = dataSource.getConnection();    // never closed: a leak            Connection second = dataSource.getConnection();   // never closed: a leak            System.out.println("Borrowed 2 connections and kept them");
            try (Connection third = dataSource.getConnection()) {                System.out.println("Got a third connection");            } catch (SQLException e) {                System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());            }        }    }}
Sample output
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
[main] INFO com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Added connection com.mysql.cj.jdbc.ConnectionImpl@696da30b
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
Borrowed 2 connections and kept them
SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 1003ms (total=2, active=2, idle=0, waiting=0)
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown initiated...
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown completed.

What this code does

  • first and second are borrowed and never closed. The third getConnection() waits for connectionTimeout (1 second here) and then throws SQLTransientConnectionException.
  • Read the numbers at the end of the message: total=2, active=2, idle=0 means every connection is borrowed. When that happens while the app is quiet, suspect a leak, not a small pool.

Example 5 · leakDetectionThreshold points at the line that borrowed

Runs in: a Maven project with the MySQL driver, HikariCP and the ShopLite database

LeakDetectionDemo.javaJava
import com.zaxxer.hikari.HikariConfig;import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;import java.sql.SQLException;
public class LeakDetectionDemo {    static void slowReport(HikariDataSource dataSource) throws SQLException, InterruptedException {        try (Connection con = dataSource.getConnection()) {            Thread.sleep(3000);                      // pretend the report holds the connection for 3 s        }    }
    public static void main(String[] args) throws SQLException, InterruptedException {        HikariConfig config = new HikariConfig();        config.setJdbcUrl(System.getenv("DB_URL"));        config.setUsername(System.getenv("DB_USER"));        config.setPassword(System.getenv("DB_PASSWORD"));        config.setMaximumPoolSize(2);        config.setLeakDetectionThreshold(2000);      // warn if a connection is out for over 2 s
        try (HikariDataSource dataSource = new HikariDataSource(config)) {            slowReport(dataSource);            System.out.println("Report finished");        }    }}
Sample output
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
[main] INFO com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Added connection com.mysql.cj.jdbc.ConnectionImpl@696da30b
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
[HikariPool-1:housekeeper] WARN com.zaxxer.hikari.pool.ProxyLeakTask - Connection leak detection triggered for com.mysql.cj.jdbc.ConnectionImpl@696da30b on thread main, stack trace follows
java.lang.Exception: Apparent connection leak detected
	at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:99)
	at LeakDetectionDemo.slowReport(LeakDetectionDemo.java:9)
	at LeakDetectionDemo.main(LeakDetectionDemo.java:23)
[main] INFO com.zaxxer.hikari.pool.ProxyLeakTask - Previously reported leaked connection com.mysql.cj.jdbc.ConnectionImpl@696da30b on thread main was returned to the pool (unleaked)
Report finished
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown initiated...
[main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown completed.

What this code does

  • The connection was out for 3 seconds, longer than the 2-second threshold, so HikariCP logged a warning with the stack trace of the getConnection() call: LeakDetectionDemo.java:9, inside slowReport.
  • Here it was not a real leak, only a slow job: when the connection came back, HikariCP logged returned to the pool (unleaked). A real leak never gets that second line.

The usual cause is a leak: a code path that borrows and never closes, such as an early return or an exception before close(). Making the pool bigger only delays the freeze. Instead, set leakDetectionThreshold (for example 2 000 ms; 0, the default, means off). Any connection held longer than that is reported with the stack trace of the line that borrowed it.

The threshold must be at least 2 000 ms, or HikariCP turns it off with a warning. Pick a value longer than your slowest normal query, or slow reports will cause false alarms.

Predict the output

Predict the third borrow

The pool holds at most 2 connections and nothing is closed. What happens at the third call?

config.setMaximumPoolSize(2);
config.setConnectionTimeout(1000);
Connection first = dataSource.getConnection();
Connection second = dataSource.getConnection();
Connection third = dataSource.getConnection();

Closing the pool on shutdown with a shutdown hook

A shutdown hook is a thread registered with Runtime.getRuntime().addShutdownHook(thread). The JVM starts it when the program stops, even on Ctrl+C, so it is the place to close the pool.

Example 6 registers a hook that closes the pool when the JVM stops, after main has finished.

Example 6 · Closing the pool when the JVM stops

Runs in: a Maven project with the MySQL driver, HikariCP and the ShopLite database

ShutdownHookDemo.javaJava
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 ShutdownHookDemo {    public static void main(String[] args) throws SQLException {        HikariConfig config = new HikariConfig();        config.setJdbcUrl(System.getenv("DB_URL"));        config.setUsername(System.getenv("DB_USER"));        config.setPassword(System.getenv("DB_PASSWORD"));        config.setPoolName("shoplite-pool");        HikariDataSource dataSource = new HikariDataSource(config);
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {            System.out.println("JVM is stopping, closing the pool");            dataSource.close();        }, "pool-closer"));
        try (Connection con = dataSource.getConnection();             Statement st = con.createStatement();             ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM orders")) {            rs.next();            System.out.println("Orders: " + rs.getInt(1));        }        System.out.println("main() is done");    }}
Sample output
[main] INFO com.zaxxer.hikari.HikariDataSource - shoplite-pool - Starting...
[main] INFO com.zaxxer.hikari.pool.HikariPool - shoplite-pool - Added connection com.mysql.cj.jdbc.ConnectionImpl@696da30b
[main] INFO com.zaxxer.hikari.HikariDataSource - shoplite-pool - Start completed.
Orders: 16
main() is done
JVM is stopping, closing the pool
[pool-closer] INFO com.zaxxer.hikari.HikariDataSource - shoplite-pool - Shutdown initiated...
[pool-closer] INFO com.zaxxer.hikari.HikariDataSource - shoplite-pool - Shutdown completed.

What this code does

  • addShutdownHook registers a thread that the JVM starts when it is about to exit: after main ends, after System.exit, or when you press Ctrl+C in the terminal.
  • The log lines now come from the pool-closer thread, after main() is done. HikariCP closes every real connection, so MySQL frees their sessions at once instead of waiting for a timeout.

dataSource.close() closes every real connection and stops HikariCP's background thread. Without it, MySQL keeps the sessions until it notices they are gone.

In a program with a clear end, try-with-resources on the HikariDataSource is enough, and the hook covers the other exits. Calling close() twice is safe, so using both is fine. A hook does not run if the process is killed hard, for example with Task Manager's End task or kill -9; MySQL then cleans up the dead sessions by itself.

Order of execution

Order the shutdown

Tap what happens, in order, when you press Ctrl+C in the terminal.

Next step

Check your understanding

12 quick questions