Practice: connection pooling and configuration
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Pooling and configuration go wrong in a handful of repeatable ways: a DriverManager call left behind, a pool sized by guesswork, a setting read in the wrong order, a connection that never goes back. Each has a quick check and a short fix.
Converting DriverManager code to a pooled DataSource
Converting to a pool takes the same four steps every time: receive a DataSource, borrow with try-with-resources, build one HikariDataSource in main, and close it when the app ends.
Example 1 · From DriverManager to one shared pool, in four steps
Runs in: a Maven project with the MySQL driver, HikariCP and the ShopLite database
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.SQLException;import javax.sql.DataSource;
// Before: every method called DriverManager.getConnection(url, user, password) itselfclass PriceLookup { private final DataSource dataSource; // step 1: receive a DataSource
PriceLookup(DataSource dataSource) { this.dataSource = dataSource; }
String priceOf(String sku) throws SQLException { String sql = "SELECT name, price FROM products WHERE sku = ?"; try (Connection con = dataSource.getConnection(); // step 2: borrow, close = give back PreparedStatement ps = con.prepareStatement(sql)) { ps.setString(1, sku); try (ResultSet rs = ps.executeQuery()) { return rs.next() ? rs.getString("name") + ": Rs " + rs.getBigDecimal("price") : sku + ": not found"; } } }}
public class CouponPoolDemo { 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"); config.setMaximumPoolSize(3);
try (HikariDataSource pool = new HikariDataSource(config)) { PriceLookup lookup = new PriceLookup(pool); for (String sku : new String[] {"BK-CLEAN", "FSH-SHOE", "NO-SUCH"}) { System.out.println(lookup.priceOf(sku)); } System.out.println("Connections opened: " + pool.getHikariPoolMXBean().getTotalConnections()); } }}[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. Clean Code: Rs 499.00 Running Shoes: Rs 2499.00 NO-SUCH: not found Connections opened: 1 [main] INFO com.zaxxer.hikari.HikariDataSource - shoplite-pool - Shutdown initiated... [main] INFO com.zaxxer.hikari.HikariDataSource - shoplite-pool - Shutdown completed.
What this code does
- The four
stepcomments are the whole recipe: the class takes aDataSource, borrows with try-with-resources,mainbuilds one pool, and the pool is closed at the end. - Three lookups ran one after another, so the pool needed only one physical connection. With
DriverManagerthat would have been three logins.
The SQL, the prepared statements and the row mapping do not change. If a converted class still mentions a URL, a password or DriverManager, the conversion is not finished.
Check the result two ways: the app behaves exactly as before, and the pool's total connections stay small while the work repeats.
Order of execution
Order the conversion
Tap the four steps of converting a DriverManager class to a pool, in order.
Choosing pool settings for a scenario
Pool settings come from a few facts: how many requests need the database at the same moment, how many copies of the app run, how strong the database server is, and how slow the slowest normal query is.
Example 2 · A small planner for pool settings
record Scenario(String name, int busyUsers, int appCopies, int dbCores, int slowestQueryMs) {}
record PoolPlan(int maxPoolSize, int connectionTimeoutMs, String note) {}
public class PoolPlanDemo { static final int MAX_CONNECTIONS = 151; // MySQL default static final int RESERVED = 10; // admin tools and the mysql client
static PoolPlan plan(Scenario s) { int bestForDb = s.dbCores() * 2 + 1; // HikariCP's starting formula, one disk int size = Math.min(s.busyUsers(), bestForDb); size = Math.max(size, 2); int budget = (MAX_CONNECTIONS - RESERVED) / s.appCopies(); String note = "fits max_connections"; if (size > budget) { size = budget; note = "capped by max_connections"; } int timeout = Math.max(2_000, s.slowestQueryMs() * 3); return new PoolPlan(size, timeout, note); }
public static void main(String[] args) { Scenario[] scenarios = { new Scenario("ShopLite console", 1, 1, 4, 50), new Scenario("Fest ticket API", 40, 2, 4, 800), new Scenario("Exam results site", 500, 12, 16, 1500), }; for (Scenario s : scenarios) { PoolPlan p = plan(s); System.out.printf("%-18s pool %2d, timeout %5d ms (%s)%n", s.name(), p.maxPoolSize(), p.connectionTimeoutMs(), p.note()); } }}ShopLite console pool 2, timeout 2000 ms (fits max_connections) Fest ticket API pool 9, timeout 2400 ms (fits max_connections) Exam results site pool 11, timeout 4500 ms (capped by max_connections)
What this code does
- The size is the smaller of "users busy at the same moment" and HikariCP's starting formula for the database server, but at least 2.
- The results site runs 12 copies of the app, so 141 free connections give each copy at most 11. More copies always means a smaller pool per copy.
- The timeout is a few times the slowest normal query and never the 30-second default, so a stuck pool shows up as a quick, clear error. These rules are a starting point to measure from, not a law.
Turn those facts into numbers:
- Size: no more than the number of truly busy requests, and near HikariCP's starting formula for the database server. One console user needs 2; a busy small API 5 to 10.
- Budget: all copies' pools together, plus admin tools, must fit under
max_connections. connectionTimeout: a few seconds, longer than the slowest normal query, so a full pool fails quickly and clearly.maxLifetime: keep the default 30 minutes unless the database or network drops connections sooner.
Predict the output
Predict the connection budget
MySQL allows 151 connections and 10 are kept for admin tools. The app runs 3 copies. What does this print?
Fixing configuration loading bugs
Configuration bugs are quiet: the app starts, but with the wrong value. The usual suspects are the override order, stray spaces, lenient parsing and missing values that become empty strings.
Example 3 · Three configuration bugs and their fixes
import java.io.IOException;import java.io.StringReader;import java.util.Map;import java.util.Properties;
public class ConfigBugsDemo { // Bug 1: the file wins over the environment, so DB_POOL_MAX_SIZE is ignored static String buggyGet(Properties file, Map<String, String> env, String key, String envName) { return file.getProperty(key, env.get(envName)); }
static String fixedGet(Properties file, Map<String, String> env, String key, String envName) { String fromEnv = env.get(envName); if (fromEnv != null && !fromEnv.isBlank()) { return fromEnv.trim(); } String fromFile = file.getProperty(key); return fromFile == null ? null : fromFile.trim(); // Bug 2 fix: trailing spaces }
public static void main(String[] args) throws IOException { Properties file = new Properties(); file.load(new StringReader("db.pool.max-size=10 \ndb.init=yes\n")); Map<String, String> env = Map.of("DB_POOL_MAX_SIZE", "4");
System.out.println("Bug 1, file wins: pool = '" + buggyGet(file, env, "db.pool.max-size", "DB_POOL_MAX_SIZE") + "'"); System.out.println("Fixed, env wins: pool = '" + fixedGet(file, env, "db.pool.max-size", "DB_POOL_MAX_SIZE") + "'");
String size = file.getProperty("db.pool.max-size"); try { Integer.parseInt(size); } catch (NumberFormatException e) { System.out.println("Bug 2, trailing space: " + e.getMessage()); } System.out.println("Fixed with trim(): " + Integer.parseInt(size.trim()));
String init = file.getProperty("db.init"); System.out.println("Bug 3, parseBoolean: db.init=" + init + " -> " + Boolean.parseBoolean(init)); boolean valid = init.equalsIgnoreCase("true") || init.equalsIgnoreCase("false"); System.out.println("Fixed, strict check: " + (valid ? "ok" : "error: db.init must be true or false, got '" + init + "'")); }}Bug 1, file wins: pool = '10 ' Fixed, env wins: pool = '4' Bug 2, trailing space: For input string: "10 " Fixed with trim(): 10 Bug 3, parseBoolean: db.init=yes -> false Fixed, strict check: error: db.init must be true or false, got 'yes'
What this code does
file.getProperty(key, env.get(name))reads like "file, or else environment": the opposite of the rule. The environment value is used only when the file has no such key.- The value
10carries the space from the file intoparseInt.yesbecomesfalsewithout any error. Each fix is one small, deliberate line.
Test the loader with small fixed inputs, exactly as the examples do with Properties and Map.of(...). A bug in the order of lookups shows up at once when the environment says 4 and the result is 10.
When a value looks right in the file but behaves wrongly, print it between quotes, '10 ', so hidden spaces become visible.
Fix the error
Fix the stray space
Read the real error, then pick the line that fixes it.
The file says db.pool.max-size=10, with a space after the 10.
Error
Exception in thread "main" java.lang.NumberFormatException: For input string: "10 "
Finding the leak that exhausts a pool
A pool leak shows up far from its cause: some code borrows without closing, and later an innocent request fails with Connection is not available, request timed out. The line in that error is never the bug.
Example 4 · Finding a leak on an exception path
Runs in: a Maven project with the MySQL driver, HikariCP and the ShopLite database
import com.zaxxer.hikari.HikariConfig;import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;import javax.sql.DataSource;
public class StockMoveLeakDemo { // Leaks when the quantity is invalid: the exception skips con.close() static void addStock(DataSource dataSource, int productId, int quantity) throws SQLException { Connection con = dataSource.getConnection(); if (quantity <= 0) { throw new IllegalArgumentException("Quantity must be positive, got " + quantity); } try (PreparedStatement ps = con.prepareStatement( "UPDATE products SET stock = stock + ? WHERE product_id = ?")) { ps.setInt(1, quantity); ps.setInt(2, productId); ps.executeUpdate(); } con.close(); }
public static void main(String[] args) throws Exception { 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(3000); config.setLeakDetectionThreshold(2000);
try (HikariDataSource pool = new HikariDataSource(config)) { int[] quantities = {0, -5, 10}; // two typos from the stock screen for (int q : quantities) { try { addStock(pool, 8, q); System.out.println("Added " + q); } catch (IllegalArgumentException e) { System.out.println("Rejected: " + e.getMessage()); } catch (SQLException e) { System.out.println("Database: " + e.getMessage()); } } } }}[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. Rejected: Quantity must be positive, got 0 Rejected: Quantity must be positive, got -5 [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 StockMoveLeakDemo.addStock(StockMoveLeakDemo.java:12) at StockMoveLeakDemo.main(StockMoveLeakDemo.java:38) [HikariPool-1:housekeeper] WARN com.zaxxer.hikari.pool.ProxyLeakTask - Connection leak detection triggered for com.mysql.cj.jdbc.ConnectionImpl@247d8ae on thread main, stack trace follows java.lang.Exception: Apparent connection leak detected at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:99) at StockMoveLeakDemo.addStock(StockMoveLeakDemo.java:12) at StockMoveLeakDemo.main(StockMoveLeakDemo.java:38) Database: HikariPool-1 - Connection is not available, request timed out after 3003ms (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
- Both rejected quantities borrowed a connection first and then threw, skipping
con.close(). The third, valid call found the pool of 2 empty and timed out. - The leak warnings name
StockMoveLeakDemo.java:12, thegetConnection()line, twice: two leaked connections, both fromaddStock. That is where to look, even though the crash happens on the third call.
Turn on leakDetectionThreshold and read the stack traces it logs: they show where the leaked connection was borrowed. Then look for paths that skip close(): an early return, an exception thrown after getConnection(), a close() that is not in finally or try-with-resources.
After the fix, getActiveConnections() must be 0 whenever no work is running. That one number is a quick test for any leak.
Find the bug
Find the leaking line
Each method borrows from the pool. Find the line that leaks a connection.
This method rejects a bad quantity.
Round 1 of 2Finish up
Mark complete & continue
Next: Mini project: pooled, configurable shoplite-console