Connection Pooling with HikariCP
Efficient connection reuse.
Connection Pooling with HikariCP is a free Java Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Pool Connections?
Opening a database connection is expensive: TCP handshake, authentication, and session setup can take tens of milliseconds.
A connection pool keeps a set of open connections ready. Your code borrows one, uses it, and returns it — turning a costly open into a cheap checkout.
Meet HikariCP
HikariCP is the de facto standard pool for Java. It is small, fast, and the default in Spring Boot.
It implements javax.sql.DataSource, so the rest of your JDBC code stays the same — you just get connections from the pool instead of DriverManager.
Configuring the Pool
You configure HikariCP with a HikariConfig object: the JDBC URL, credentials, and pool sizing.
Then you create a HikariDataSource from it. This is typically done once at application startup and shared.
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
public class Main {
public static void main(String[] args) {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:postgresql://localhost:5432/shop");
config.setUsername("app");
config.setPassword("secret");
config.setMaximumPoolSize(10);
HikariDataSource ds = new HikariDataSource(config);
System.out.println("Pool ready, max size " + config.getMaximumPoolSize());
ds.close();
}
}Borrowing a Connection
Call ds.getConnection() to borrow. Wrap it in try-with-resources as usual.
Here is the key insight: closing a pooled connection does not close the physical socket — it returns the connection to the pool for reuse.
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
public class Main {
public static void main(String[] args) {
DataSource ds = new HikariDataSource();
try (Connection conn = ds.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT count(*) FROM users");
ResultSet rs = ps.executeQuery()) {
if (rs.next()) System.out.println("Users: " + rs.getInt(1));
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}close() Means Return
This trips up many developers. With a pool:
conn.close()returns the connection to the pool.- The pool keeps the real socket open for the next borrower.
So you should still always close — try-with-resources is correct. You are returning, not destroying.
Pool Sizing
Bigger is not better. A pool that is too large overwhelms the database with concurrent work.
The HikariCP guidance: a small pool, often around (core_count * 2) + effective_spindle_count, usually beats a huge one. maximumPoolSize is the cap; minimumIdle keeps a few warm.
public class Main {
public static void main(String[] args) {
int cores = 4;
int spindles = 1; // SSD-ish
int recommended = (cores * 2) + spindles;
System.out.println("Suggested max pool size: " + recommended);
}
}Key Timeouts
HikariCP exposes timeouts that protect your app from a stuck database:
connectionTimeout— how long a borrow waits before failing (default 30s).idleTimeout— how long an idle connection lives.maxLifetime— retire a connection after this age (keep it below the DB's own timeout).
Connection Validation
Networks drop connections silently. Before handing one out, HikariCP can validate it.
Modern JDBC drivers use Connection.isValid(timeout); HikariCP calls it automatically. You can also set connectionTestQuery for old drivers that lack isValid.
Leak Detection
A connection leak happens when code borrows but never closes — eventually the pool runs dry and every borrow times out.
Set leakDetectionThreshold (e.g. 20000 ms) and HikariCP logs a stack trace for any connection held longer than that, pointing you straight at the offending code.
One Pool Per App
Create the HikariDataSource once and reuse it for the whole application lifetime.
Creating a new pool per request defeats the purpose — you would pay startup cost every time. Close the pool only at shutdown with ds.close().
Monitoring the Pool
HikariCP exposes runtime metrics so you can watch pool health.
- Active, idle, and total connections.
- Threads currently awaiting a connection.
It integrates with Micrometer, Dropwizard Metrics, and JMX. A persistently high 'awaiting' count means the pool is too small or connections are being held too long.
Quick Check
When using HikariCP, what does calling close() on a borrowed connection do?
Recap
HikariCP makes connection reuse efficient:
- Configure a
HikariDataSourceonce at startup. - Borrow with
getConnection()in try-with-resources;close()returns it to the pool. - Keep
maximumPoolSizemodest. - Tune
connectionTimeout,maxLifetime, and validation. - Use
leakDetectionThresholdto catch un-returned connections.
Frequently asked questions
Is the “Connection Pooling with HikariCP” lesson free?
Yes — the full text of “Connection Pooling with HikariCP” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Connection Pooling with HikariCP”?
Efficient connection reuse. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Connection Pooling with HikariCP” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- JDBC Fundamentals
- PreparedStatement
- Transactions
- Connection Pooling with HikariCP