Connection Pools, DataSources and JPA: JDBC in Real Applications
How server applications manage database connections: why pools exist and how they work, HikariCP settings and pool sizing, pools with virtual threads, DataSources from JNDI, @Resource and Spring Boot, distributed transactions, and the persistence layers built on JDBC: JdbcClient, jOOQ and JPA.
kvi5hnuCode Sprout team member11 min readOn this page
The earlier articles opened a connection, did some work and closed it again. That's fine for tools and tests, but not for a server that handles hundreds of requests per second. Opening a physical connection means a TCP handshake, often TLS, authentication and session setup, which takes milliseconds to tens of milliseconds and uses memory and a process or thread on the database server. Keeping one connection per user open isn't an option either, because databases support only a limited number of connections. The answer is a connection pool. This final article of the database part shows how pools work, how to configure them, and what sits on top of JDBC in typical applications.
How a connection pool works
A pool keeps a set of open physical connections. When code calls dataSource.getConnection(), the pool hands out an idle connection, or opens a new one if it's below its maximum, or makes the caller wait. What the caller receives is a wrapper (a proxy). Its close() doesn't close the physical connection. It resets the connection and returns it to the pool.
For application code, pooling is invisible. You obtain connections from a DataSource and close them with try-with-resources, exactly as before. That's why code should depend on DataSource (article 58) rather than DriverManager.
A good pool also:
- Validates connections before handing them out, usually with
Connection.isValid, and replaces broken ones, for example after a database restart or a firewall dropping idle connections. - Resets state on return: it rolls back an open transaction and restores auto-commit, isolation level and read-only flags. JDBC 4.3 added
Connection.beginRequest()andendRequest()so that pools can tell the driver where one unit of work ends. - Retires connections after a maximum lifetime, before the database or the network does it at an inconvenient moment.
- Times out waiting callers instead of letting them hang, typically with an
SQLTransientConnectionException. - Detects leaks: it logs a stack trace when a connection is held suspiciously long, which points to code that forgot to close it.
- Caches prepared statements per connection, or leaves that to the driver.
JDBC defines interfaces for pool implementers, ConnectionPoolDataSource and PooledConnection with ConnectionEventListener, so that drivers can supply physical connections to any pool. Most modern pools just wrap ordinary DataSource or Driver connections.
Pool implementations
The JDK doesn't include a pool. Common choices:
- HikariCP: small and fast, and the default in Spring Boot.
- Agroal: used by Quarkus. Tomcat JDBC and Apache Commons DBCP: found in older Tomcat-based deployments.
- Oracle UCP: Oracle's pool, with features for Oracle RAC.
- Application servers (WildFly, Payara, Open Liberty and others) have built-in pools configured by the administrator.
- Some drivers and embedded databases include a simple one, such as H2's
JdbcConnectionPool.
A typical HikariCP setup:
var config = new HikariConfig();
config.setJdbcUrl("jdbc:postgresql://db.example.com/shop");
config.setUsername("shop");
config.setPassword(System.getenv("DB_PASSWORD"));
config.setMaximumPoolSize(10);
config.setConnectionTimeout(3_000); // ms to wait for a connection before failing
config.setMaxLifetime(1_800_000); // retire connections after 30 minutes
config.setLeakDetectionThreshold(10_000); // warn if a connection is held for 10 s
DataSource dataSource = new HikariDataSource(config);
In Spring Boot, the same comes from configuration properties such as spring.datasource.url and spring.datasource.hikari.maximum-pool-size.
Pool sizing
Bigger isn't better. A database server can only work on as many queries at once as it has CPU cores and disk capacity to serve. Beyond that, extra connections just compete for the same resources, adding context switches and lock contention. Pools of 10 to 30 connections per application instance are common even for busy services. A frequently quoted starting point is about twice the database server's core count, divided among all application instances that share the database. Measure, then adjust. Requests that queue briefly for a connection usually finish sooner than a database that is overloaded with connections.
Pools and virtual threads
With virtual threads (Java 21), a server can easily have thousands of concurrent requests, far more than the pool has connections. That's fine: the pool bounds how many talk to the database at once, and the rest wait cheaply for a connection. Size the connection timeout so that waits fail clearly under overload. Before Java 24, JDBC drivers that used synchronized while doing blocking I/O could pin a virtual thread to its carrier thread and reduce throughput. JEP 491 (Java 24) removed that limitation, and current drivers have also replaced most such locks.
DataSources in enterprise applications
In Jakarta EE application servers, data sources are defined by the administrator (URL, credentials, pool settings) and registered in the JNDI directory under a name. Code looks them up or, more commonly, has them injected:
// explicit lookup
var source = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/shop");
// injection by the container
@Resource(lookup = "java:comp/env/jdbc/shop")
private DataSource source;
An application can also declare a data source itself with the @DataSourceDefinition annotation. Credentials stay in the server's configuration, the application contains only the name, and the same build runs against test and production databases.
Frameworks such as Spring, Quarkus and Micronaut create the pooled DataSource from configuration and inject it into the classes that need it.
Distributed transactions
A local transaction (article 65) covers one connection. A transaction that spans two databases, or a database and a message broker, needs a transaction manager that coordinates them with two-phase commit. JDBC supports this through XADataSource and XAConnection, which expose an XAResource. Jakarta Transactions (JTA) in application servers, or standalone managers such as Narayana and Atomikos, do the coordination. Two-phase commit is complex and slow. Many modern systems avoid it with patterns like the transactional outbox, where the message is written to a table in the same local transaction and published afterward.
Above JDBC: persistence layers
Writing PreparedStatement code by hand gets repetitive: set parameters, loop over rows, map columns to objects, handle resources and exceptions. Most applications use a layer on top:
- Thin helpers such as Spring's
JdbcClient(Spring 6.1),JdbcTemplateand Jdbi keep you writing SQL but handle resources, parameter binding and row mapping. For example,jdbcClient.sql("SELECT * FROM products WHERE price < ?").param(limit).query(Product.class).list()maps rows directly to a record. - Type-safe SQL builders like jOOQ generate Java classes from the schema, so queries are checked by the compiler.
- SQL mappers like MyBatis keep SQL in XML or annotations and map results to objects.
- Object-relational mapping with Jakarta Persistence (JPA). The current version is 3.2, part of Jakarta EE 11, implemented by Hibernate ORM 7 and EclipseLink. You map entity classes to tables with annotations, and the
EntityManagerloads, tracks and saves objects, generating the SQL. Spring Data JPA adds repository interfaces whose queries are derived from method names.
All of them use JDBC connections from a pool underneath. Schema changes are typically versioned with migration tools such as Flyway or Liquibase, and integration tests run against real databases started by Testcontainers. Knowing JDBC is what lets you understand and debug every one of these layers.
Trying it with H2
H2 ships a simple pool, JdbcConnectionPool. The repository class below depends only on DataSource and maps rows to a record:
import java.math.BigDecimal;
import java.sql.*;
import java.util.*;
import javax.sql.DataSource;
import org.h2.jdbcx.JdbcConnectionPool;
public class PoolDemo {
record Product(int id, String name, BigDecimal price) { }
// Data access code depends only on DataSource
static class ProductRepository {
private final DataSource dataSource;
ProductRepository(DataSource dataSource) { this.dataSource = dataSource; }
List<Product> cheaperThan(BigDecimal limit) throws SQLException {
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT id, name, price FROM products WHERE price < ? ORDER BY price")) {
ps.setBigDecimal(1, limit);
try (ResultSet rs = ps.executeQuery()) {
var result = new ArrayList<Product>();
while (rs.next()) result.add(new Product(rs.getInt("id"), rs.getString("name"), rs.getBigDecimal("price")));
return result;
}
}
}
}
public static void main(String[] args) throws SQLException {
JdbcConnectionPool pool = JdbcConnectionPool.create("jdbc:h2:mem:shop;DB_CLOSE_DELAY=-1", "sa", "");
pool.setMaxConnections(5);
try (Connection conn = pool.getConnection(); Statement stat = conn.createStatement()) {
stat.executeUpdate("CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(40), price DECIMAL(8,2))");
stat.executeUpdate("INSERT INTO products VALUES (1, 'Hammer', 12.50), (2, 'Oak shelf', 89.90), (3, 'Saw', 19.00)");
}
var repository = new ProductRepository(pool);
for (int i = 0; i < 3; i++) repository.cheaperThan(new BigDecimal("50"));
System.out.println(repository.cheaperThan(new BigDecimal("50")));
System.out.println("active connections: " + pool.getActiveConnections() + ", max " + pool.getMaxConnections());
try (Connection borrowed = pool.getConnection()) {
System.out.println("while one is borrowed: " + pool.getActiveConnections() + ", valid " + borrowed.isValid(1));
}
pool.dispose();
}
}
Output with H2 2.3:
[Product[id=1, name=Hammer, price=12.50], Product[id=3, name=Saw, price=19.00]]
active connections: 0, max 5
while one is borrowed: 1, valid true
After the queries, no connection is active: every close() returned its connection to the pool.
The program
The runnable demo implements a tiny pool to show the mechanics. TinyPool limits the number of connections with a fair Semaphore, creates physical connections lazily (stand-ins built with dynamic proxies), validates idle connections before reuse, and hands out proxies whose close() returns the connection. On return, it rolls back any transaction left open. 200 requests on virtual threads share a pool of four. Then the demo provokes the problems a pool guards against: a forgotten transaction, an exhausted pool that times out, a double close(), and use after close. Finally, a small query helper maps rows to records the way JdbcClient does.
import java.io.PrintWriter;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.sql.*;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.logging.Logger;
import javax.sql.DataSource;
import javax.sql.RowSetMetaData;
import javax.sql.rowset.*;
public class Solution {
// ---------- a stand-in for a physical database connection ----------
static final AtomicInteger physicalOpened = new AtomicInteger();
static Connection physicalConnection(int id) {
physicalOpened.incrementAndGet();
var state = new Object() { boolean closed, autoCommit = true, inTransaction; };
return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class<?>[] { Connection.class },
(proxy, method, args) -> switch (method.getName()) {
case "isValid" -> !state.closed;
case "isClosed" -> state.closed;
case "close" -> { state.closed = true; yield null; }
case "getAutoCommit" -> state.autoCommit;
case "setAutoCommit" -> { state.autoCommit = (Boolean) args[0]; yield null; }
case "nativeSQL" -> { if (!state.autoCommit) state.inTransaction = true; yield args[0]; } // "run a statement"
case "rollback" -> { state.inTransaction = false; yield null; }
case "commit" -> { state.inTransaction = false; yield null; }
case "getClientInfo" -> state.inTransaction ? "open transaction" : "clean";
case "toString" -> "physical#" + id;
case "hashCode" -> id;
case "equals" -> proxy == args[0];
default -> throw new SQLFeatureNotSupportedException(method.getName());
});
}
// ---------- a minimal connection pool ----------
static class TinyPool implements DataSource, AutoCloseable {
private final int maxSize;
private final Duration borrowTimeout;
private final Semaphore permits;
private final BlockingDeque<Connection> idle = new LinkedBlockingDeque<>();
private final AtomicInteger created = new AtomicInteger(), inUse = new AtomicInteger(), maxInUse = new AtomicInteger();
final List<String> events = Collections.synchronizedList(new ArrayList<>());
TinyPool(int maxSize, Duration borrowTimeout) {
this.maxSize = maxSize;
this.borrowTimeout = borrowTimeout;
this.permits = new Semaphore(maxSize, true);
}
@Override public Connection getConnection() throws SQLException {
try {
if (!permits.tryAcquire(borrowTimeout.toMillis(), TimeUnit.MILLISECONDS))
throw new SQLTransientConnectionException("pool exhausted: no connection within " + borrowTimeout.toMillis() + " ms", "08001");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new SQLException("interrupted while waiting for a connection", e);
}
Connection physical = idle.pollFirst();
if (physical != null && !physical.isValid(1)) { // validate before handing out
events.add("discarded broken " + physical);
physical = null;
}
if (physical == null) physical = physicalConnection(created.incrementAndGet());
int now = inUse.incrementAndGet();
maxInUse.accumulateAndGet(now, Math::max);
return wrap(physical);
}
// The application gets a proxy whose close() returns the physical connection to the pool
private Connection wrap(Connection physical) {
var returned = new AtomicBoolean();
return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class<?>[] { Connection.class },
(proxy, method, args) -> {
if (method.getName().equals("close")) {
if (returned.compareAndSet(false, true)) giveBack(physical);
return null;
}
if (method.getName().equals("isClosed")) return returned.get();
if (returned.get()) throw new SQLException("connection already returned to the pool");
try { return method.invoke(physical, args); }
catch (java.lang.reflect.InvocationTargetException e) { throw e.getCause(); }
});
}
private void giveBack(Connection physical) throws SQLException {
if (!physical.getAutoCommit()) { // never hand on an open transaction
if (physical.getClientInfo("").equals("open transaction")) events.add("rolled back a forgotten transaction on " + physical);
physical.rollback();
physical.setAutoCommit(true);
}
idle.addFirst(physical); // most recently used first
inUse.decrementAndGet();
permits.release();
}
@Override public void close() throws SQLException {
for (Connection c; (c = idle.poll()) != null; ) c.close();
}
String stats() { return "created " + created.get() + ", max in use " + maxInUse.get() + ", idle " + idle.size() + " (limit " + maxSize + ")"; }
@Override public Connection getConnection(String u, String p) throws SQLException { return getConnection(); }
@Override public PrintWriter getLogWriter() { return null; }
@Override public void setLogWriter(PrintWriter out) { }
@Override public void setLoginTimeout(int seconds) { }
@Override public int getLoginTimeout() { return 0; }
@Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException(); }
@Override public <T> T unwrap(Class<T> iface) throws SQLException { throw new SQLException("not a wrapper"); }
@Override public boolean isWrapperFor(Class<?> iface) { return false; }
}
// ---------- mapping rows to records, as JdbcClient or jOOQ would ----------
@FunctionalInterface interface RowMapper<T> { T map(ResultSet rs) throws SQLException; }
static <T> List<T> query(ResultSet rs, RowMapper<T> mapper) throws SQLException {
var result = new ArrayList<T>();
try (rs) { while (rs.next()) result.add(mapper.map(rs)); }
return result;
}
record Product(int id, String name, BigDecimal price) { }
static ResultSet productRows() throws SQLException {
CachedRowSet rs = RowSetProvider.newFactory().createCachedRowSet();
RowSetMetaData meta = new RowSetMetaDataImpl();
meta.setColumnCount(3);
meta.setColumnName(1, "ID"); meta.setColumnType(1, Types.INTEGER);
meta.setColumnName(2, "NAME"); meta.setColumnType(2, Types.VARCHAR);
meta.setColumnName(3, "PRICE"); meta.setColumnType(3, Types.DECIMAL);
for (int i = 1; i <= 3; i++) meta.setColumnLabel(i, meta.getColumnName(i));
rs.setMetaData(meta);
Object[][] rows = { { 1, "Hammer", "12.50" }, { 2, "Oak shelf", "89.90" } };
for (Object[] row : rows) {
rs.moveToInsertRow();
rs.updateInt(1, (Integer) row[0]);
rs.updateString(2, (String) row[1]);
rs.updateBigDecimal(3, new BigDecimal((String) row[2]));
rs.insertRow();
}
rs.moveToCurrentRow();
rs.beforeFirst();
return rs;
}
public static void main(String[] args) throws Exception {
System.out.println("--- 200 requests on virtual threads share a pool of 4 ---");
try (var pool = new TinyPool(4, Duration.ofSeconds(5));
var executor = Executors.newVirtualThreadPerTaskExecutor()) {
var done = new AtomicInteger();
for (int i = 0; i < 200; i++) {
executor.submit(() -> {
try (Connection conn = pool.getConnection()) {
conn.nativeSQL("SELECT ..."); // pretend to query
Thread.sleep(5);
done.incrementAndGet();
}
return null;
});
}
executor.shutdown();
executor.awaitTermination(30, TimeUnit.SECONDS);
System.out.println("requests done: " + done.get() + ", physical connections opened: " + physicalOpened.get());
System.out.println(pool.stats());
}
System.out.println("--- what the pool protects against ---");
try (var pool = new TinyPool(2, Duration.ofMillis(100))) {
Connection a = pool.getConnection();
a.setAutoCommit(false);
a.nativeSQL("UPDATE accounts ..."); // forgot to commit or roll back
a.close(); // pool rolls back before reuse
System.out.println("events: " + pool.events);
Connection b = pool.getConnection();
Connection c = pool.getConnection();
try {
pool.getConnection(); // a leak elsewhere: all connections taken
} catch (SQLTransientConnectionException e) {
System.out.println(e.getMessage() + " [" + e.getSQLState() + "]");
}
b.close();
b.close(); // closing twice is harmless
try {
b.nativeSQL("SELECT 1");
} catch (SQLException e) {
System.out.println("using a returned connection: " + e.getMessage());
}
c.close();
System.out.println(pool.stats());
}
System.out.println("--- mapping rows to records ---");
List<Product> products = query(productRows(),
rs -> new Product(rs.getInt("ID"), rs.getString("NAME"), rs.getBigDecimal("PRICE")));
products.forEach(System.out::println);
}
}
--- 200 requests on virtual threads share a pool of 4 ---
requests done: 200, physical connections opened: 4
created 4, max in use 4, idle 4 (limit 4)
--- what the pool protects against ---
events: [rolled back a forgotten transaction on physical#1]
pool exhausted: no connection within 100 ms [08001]
using a returned connection: connection already returned to the pool
created 2, max in use 2, idle 2 (limit 2)
--- mapping rows to records ---
Product[id=1, name=Hammer, price=12.50]
Product[id=2, name=Oak shelf, price=89.90]
Only four physical connections served all 200 requests. Real pools add much more, such as health checks, metrics, maximum lifetimes, leak detection and statement caching, but the core idea is the same.
Common questions
What does "Connection is not available, request timed out after 30000ms" mean?
HikariCP's pool was empty for the whole connection timeout. Usual causes: connections leaked (not closed), transactions or queries that are too slow, or more concurrent work than the pool size. Turn on leak detection (leakDetectionThreshold), check slow queries, and only then consider a larger pool.
How do I find a connection leak?
Leak detection in the pool logs a stack trace of where a connection was borrowed but not returned in time. The fix is almost always a missing try-with-resources around getConnection().
Should each microservice instance have its own pool? Yes, each instance has its own. Remember that the database sees the sum: 20 instances with 20 connections each is 400 connections. For many instances, an external pooler such as PgBouncer can multiplex them.
Do I need a pool with virtual threads? Yes. Virtual threads make waiting cheap, but the database still can't handle unlimited connections. The pool, or a semaphore, is what limits concurrency against the database.
JPA or plain JDBC/JdbcClient?
JPA saves code for rich domain models with relationships and object graphs, at the cost of complexity (lazy loading, flush timing, generated SQL). For reporting, bulk operations and simple CRUD, plain SQL with a thin helper is often clearer. Many applications use both.
API reference
| API | Purpose |
|---|---|
javax.sql.DataSource.getConnection(), Connection.close() | borrow and return a pooled connection |
Connection.isValid(seconds) | validation used by pools |
Connection.beginRequest(), endRequest() | mark units of work for pools (JDBC 4.3) |
javax.sql.ConnectionPoolDataSource, PooledConnection, ConnectionEventListener | interfaces between drivers and pools |
javax.sql.XADataSource, XAConnection, getXAResource() | distributed transactions |
InitialContext.lookup(name), @Resource, @DataSourceDefinition | data sources in Jakarta EE |
SQLTransientConnectionException | typical failure when no connection is available in time |
Summary
- Opening connections is expensive and databases allow only a limited number, so server applications borrow connections from a pool through a
DataSource. Closing a pooled connection returns it. - Pools validate, reset, retire and time out connections, and can detect leaks. HikariCP is the common choice, and application servers bring their own.
- Keep pools small, measured against the database's capacity. With virtual threads, the pool limits concurrent database work while thousands of requests wait cheaply.
- In Jakarta EE, data sources come from JNDI or
@Resource, and frameworks inject them from configuration. XA data sources support distributed transactions. - Most applications use JdbcClient, jOOQ, MyBatis or JPA on top of JDBC. Understanding JDBC makes all of them easier to use well.
Practice Questions
Your code calls conn.close() on a connection from a HikariCP data source. Is the TCP connection to the database closed?
No. The connection you received is a proxy. Its close() resets the connection's state (rolling back an open transaction, restoring auto-commit and so on) and returns the physical connection to the pool for the next borrower. The physical connection closes only when the pool retires it or shuts down.
Under load, requests fail with "Connection is not available, request timed out after 30000ms". What are the likely causes?
All pool connections were in use for the whole timeout. Common causes are connection leaks (code that doesn't close connections, often missing try-with-resources), long-running queries or transactions holding connections, and a pool that really is too small for the load. Turn on leak detection, check slow queries, and only then consider a larger pool.
Why can a pool of 10 connections outperform one of 200 for the same database?
The database can only execute about as many queries in parallel as it has cores and I/O capacity. With 200 active connections, queries compete for CPU, memory and locks, and context switching and contention slow everything down. With 10, queries run at full speed while other requests wait briefly in the pool's queue, so the total throughput is often higher and latency more predictable.
An application runs 10,000 virtual threads that all need the database, with a pool of 20 connections. Is that a problem?
Not in itself. At most 20 threads use the database at a time, and the others block cheaply, as virtual threads do, until a connection is free. Set a sensible connection timeout so that overload shows up as fast failures instead of growing queues. If many threads also hold connections while waiting for other services, restructure the code to hold connections only for the database work.
What does an application server gain by managing the DataSource instead of the application creating it?
Configuration and credentials live outside the application, so the same build can be deployed against different databases and passwords never appear in the code. The administrator can tune and monitor the pool. The server can also enlist connections in JTA transactions, including distributed XA transactions, and the application only needs the JNDI name.
Previous: JDBC Transactions: Commit, Rollback, Isolation, Save Points and Batch Updates
Next: Instant and Duration in Java: Points and Spans on the Time Line
Related reading
- JDBC Transactions: Commit, Rollback, Isolation, Save Points and Batch Updates
- JDBC Metadata: DatabaseMetaData, ResultSetMetaData and ParameterMetaData
- JDBC Row Sets: CachedRowSet, WebRowSet, FilteredRowSet and JoinRowSet
- Scrollable and Updatable Result Sets in JDBC
- LOBs, SQL Escapes, Multiple Results and Generated Keys in JDBC

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.