0
# Connection Pooling
1
2
Core connection pool functionality for creating and managing database connections efficiently with minimal overhead.
3
4
## Capabilities
5
6
### HikariDataSource
7
8
The main entry point for HikariCP providing DataSource implementation with connection pooling.
9
10
```java { .api }
11
/**
12
* The HikariCP pooled DataSource implementation
13
* Extends HikariConfig to inherit all configuration capabilities
14
* Implements standard JDBC DataSource interface
15
*/
16
public class HikariDataSource extends HikariConfig implements DataSource, Closeable {
17
18
/**
19
* Default constructor for lazy initialization
20
* Pool starts on first getConnection() call
21
*/
22
public HikariDataSource();
23
24
/**
25
* Pre-configured constructor that starts the pool immediately
26
* @param configuration HikariConfig instance with connection settings
27
*/
28
public HikariDataSource(HikariConfig configuration);
29
30
/**
31
* Get a connection from the pool
32
* @return Connection from the pool
33
* @throws SQLException if connection cannot be obtained
34
*/
35
public Connection getConnection() throws SQLException;
36
37
/**
38
* DataSource method for username/password connections
39
* @throws SQLFeatureNotSupportedException - not supported by HikariCP
40
*/
41
public Connection getConnection(String username, String password) throws SQLException;
42
43
/**
44
* Check if the pool is running and not suspended or shutdown
45
* @return true if pool is operational
46
*/
47
public boolean isRunning();
48
49
/**
50
* Evict a specific connection from the pool
51
* @param connection the connection to evict
52
*/
53
public void evictConnection(Connection connection);
54
55
/**
56
* Shutdown the DataSource and its connection pool
57
*/
58
public void close();
59
60
/**
61
* Check if the DataSource has been closed
62
* @return true if closed
63
*/
64
public boolean isClosed();
65
66
/**
67
* Get the pool management MXBean
68
* @return HikariPoolMXBean for JMX management
69
*/
70
public HikariPoolMXBean getHikariPoolMXBean();
71
72
/**
73
* Get the configuration management MXBean
74
* @return HikariConfigMXBean for JMX configuration management
75
*/
76
public HikariConfigMXBean getHikariConfigMXBean();
77
}
78
```
79
80
**Usage Examples:**
81
82
```java
83
import com.zaxxer.hikari.HikariConfig;
84
import com.zaxxer.hikari.HikariDataSource;
85
86
// Lazy initialization approach
87
HikariDataSource dataSource = new HikariDataSource();
88
dataSource.setJdbcUrl("jdbc:postgresql://localhost/test");
89
dataSource.setUsername("postgres");
90
dataSource.setPassword("password");
91
dataSource.setMaximumPoolSize(10);
92
93
// Pool starts when first connection is requested
94
Connection conn = dataSource.getConnection();
95
96
// Pre-configured approach
97
HikariConfig config = new HikariConfig();
98
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
99
config.setUsername("user");
100
config.setPassword("pass");
101
config.setMaximumPoolSize(20);
102
config.setConnectionTimeout(30000);
103
104
// Pool starts immediately
105
HikariDataSource dataSource = new HikariDataSource(config);
106
107
// Check pool status
108
if (dataSource.isRunning()) {
109
System.out.println("Pool is operational");
110
}
111
112
// Clean shutdown
113
dataSource.close();
114
```
115
116
### Connection Management
117
118
HikariCP provides sophisticated connection management with leak detection and proxy wrapping.
119
120
**Connection Lifecycle:**
121
122
```java
123
// Obtain connection from pool
124
try (Connection connection = dataSource.getConnection()) {
125
// Connection is wrapped in HikariCP proxy
126
// Automatically returned to pool when closed
127
128
PreparedStatement stmt = connection.prepareStatement("SELECT * FROM users WHERE id = ?");
129
stmt.setLong(1, userId);
130
ResultSet rs = stmt.executeQuery();
131
132
// Process results
133
while (rs.next()) {
134
// Handle row data
135
}
136
137
// Statements and ResultSets are also proxied for proper cleanup
138
} // Connection automatically returned to pool here
139
```
140
141
**Connection Eviction:**
142
143
```java
144
// Force eviction of specific connection
145
Connection problematicConnection = dataSource.getConnection();
146
// ... detect connection issue
147
dataSource.evictConnection(problematicConnection);
148
149
// Soft eviction of all idle connections (via JMX)
150
HikariPoolMXBean poolMBean = dataSource.getHikariPoolMXBean();
151
poolMBean.softEvictConnections(); // Evicts idle connections immediately
152
```
153
154
### DataSource Interface Implementation
155
156
HikariDataSource implements the standard JDBC DataSource interface.
157
158
```java { .api }
159
// Standard DataSource methods
160
public PrintWriter getLogWriter() throws SQLException;
161
public void setLogWriter(PrintWriter out) throws SQLException;
162
public void setLoginTimeout(int seconds) throws SQLException;
163
public int getLoginTimeout() throws SQLException;
164
165
// JDBC 4.1 methods
166
public Logger getParentLogger() throws SQLFeatureNotSupportedException; // Not supported
167
168
// Wrapper methods for accessing underlying DataSource
169
public <T> T unwrap(Class<T> iface) throws SQLException;
170
public boolean isWrapperFor(Class<?> iface) throws SQLException;
171
```
172
173
**Integration with Application Servers:**
174
175
```java
176
// For application server integration
177
import javax.naming.InitialContext;
178
import javax.sql.DataSource;
179
180
// DataSource can be bound to JNDI
181
InitialContext ctx = new InitialContext();
182
ctx.bind("java:comp/env/jdbc/MyDB", dataSource);
183
184
// Later retrieval
185
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/MyDB");
186
```
187
188
### Connection Pool Statistics
189
190
Real-time pool statistics available through the management interface.
191
192
```java { .api }
193
/**
194
* Get real-time pool statistics
195
*/
196
HikariPoolMXBean poolMBean = dataSource.getHikariPoolMXBean();
197
198
int active = poolMBean.getActiveConnections(); // Connections in use
199
int idle = poolMBean.getIdleConnections(); // Available connections
200
int total = poolMBean.getTotalConnections(); // Total pool size
201
int waiting = poolMBean.getThreadsAwaitingConnection(); // Threads waiting for connections
202
```
203
204
**Monitoring Example:**
205
206
```java
207
import com.zaxxer.hikari.HikariPoolMXBean;
208
209
public void monitorPool(HikariDataSource dataSource) {
210
HikariPoolMXBean poolBean = dataSource.getHikariPoolMXBean();
211
212
if (poolBean != null) {
213
System.out.printf("Pool Stats - Active: %d, Idle: %d, Total: %d, Waiting: %d%n",
214
poolBean.getActiveConnections(),
215
poolBean.getIdleConnections(),
216
poolBean.getTotalConnections(),
217
poolBean.getThreadsAwaitingConnection());
218
219
// Check for potential issues
220
if (poolBean.getThreadsAwaitingConnection() > 0) {
221
System.out.println("Warning: Threads waiting for connections");
222
}
223
}
224
}
225
```
226
227
### Pool Suspension and Resumption
228
229
HikariCP supports pool suspension for maintenance operations.
230
231
```java { .api }
232
/**
233
* Suspend and resume pool operations
234
* Requires setAllowPoolSuspension(true) in configuration
235
*/
236
HikariPoolMXBean poolMBean = dataSource.getHikariPoolMXBean();
237
238
// Suspend pool - new getConnection() calls will block
239
poolMBean.suspendPool();
240
241
// Perform maintenance operations
242
// ...
243
244
// Resume normal operations
245
poolMBean.resumePool();
246
```
247
248
**Maintenance Example:**
249
250
```java
251
public void performMaintenance(HikariDataSource dataSource) {
252
HikariPoolMXBean poolBean = dataSource.getHikariPoolMXBean();
253
254
try {
255
// Suspend pool to prevent new connections
256
poolBean.suspendPool();
257
System.out.println("Pool suspended for maintenance");
258
259
// Evict all idle connections
260
poolBean.softEvictConnections();
261
262
// Perform database maintenance
263
// ...
264
265
} finally {
266
// Always resume the pool
267
poolBean.resumePool();
268
System.out.println("Pool resumed");
269
}
270
}