or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced.mdconfiguration.mddatasource.mdhibernate.mdindex.mdmetrics.mdmonitoring.md

advanced.mddocs/

0

# Advanced Features

1

2

HikariCP provides several advanced features for enterprise deployments including JNDI factory support, custom exception handling, and advanced configuration options for specialized use cases.

3

4

## Capabilities

5

6

### JNDI Factory Support

7

8

Factory implementation for creating HikariDataSource instances through JNDI lookups, enabling application server integration and container-managed connection pools.

9

10

```java { .api }

11

/**

12

* JNDI factory for creating HikariDataSource instances

13

*/

14

public class HikariJNDIFactory implements ObjectFactory {

15

/**

16

* Create HikariDataSource instance from JNDI reference

17

* @param obj Reference object containing configuration

18

* @param name JNDI name being looked up

19

* @param nameCtx JNDI naming context

20

* @param environment Environment properties

21

* @return Configured HikariDataSource instance

22

* @throws Exception If DataSource creation fails

23

*/

24

public synchronized Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception;

25

}

26

```

27

28

**JNDI Configuration Example:**

29

30

```xml

31

<!-- In server.xml or context.xml -->

32

<Resource name="jdbc/MyDataSource"

33

auth="Container"

34

type="javax.sql.DataSource"

35

factory="com.zaxxer.hikari.HikariJNDIFactory"

36

jdbcUrl="jdbc:mysql://localhost:3306/mydb"

37

username="dbuser"

38

password="dbpass"

39

maximumPoolSize="10"

40

minimumIdle="5" />

41

```

42

43

**Usage in Application:**

44

45

```java

46

import javax.naming.Context;

47

import javax.naming.InitialContext;

48

import javax.sql.DataSource;

49

50

// Lookup DataSource via JNDI

51

Context ctx = new InitialContext();

52

DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/MyDataSource");

53

54

// Use DataSource normally

55

try (Connection conn = dataSource.getConnection()) {

56

// Database operations

57

}

58

```

59

60

### Custom Exception Handling

61

62

Interface for implementing custom SQLException handling and connection eviction decisions, allowing fine-grained control over error handling behavior.

63

64

```java { .api }

65

/**

66

* Interface for custom SQLException handling and connection eviction decisions

67

*/

68

public interface SQLExceptionOverride {

69

/**

70

* Override decision enum for connection eviction

71

*/

72

enum Override {

73

/** Continue with default eviction behavior */

74

CONTINUE_EVICT,

75

/** Do not evict the connection */

76

DO_NOT_EVICT

77

}

78

79

/**

80

* Decide whether to evict connection based on SQLException

81

* @param sqlException The SQLException that occurred

82

* @return Override decision for connection eviction

83

*/

84

default Override adjudicate(final SQLException sqlException);

85

}

86

```

87

88

**Custom Exception Handler Example:**

89

90

```java

91

import com.zaxxer.hikari.SQLExceptionOverride;

92

import java.sql.SQLException;

93

94

public class CustomExceptionOverride implements SQLExceptionOverride {

95

@Override

96

public Override adjudicate(SQLException sqlException) {

97

// Don't evict connections for specific error codes

98

String sqlState = sqlException.getSQLState();

99

int errorCode = sqlException.getErrorCode();

100

101

// MySQL specific: Don't evict for lock wait timeout

102

if ("HY000".equals(sqlState) && errorCode == 1205) {

103

return Override.DO_NOT_EVICT;

104

}

105

106

// PostgreSQL specific: Don't evict for query cancellation

107

if ("57014".equals(sqlState)) {

108

return Override.DO_NOT_EVICT;

109

}

110

111

// For all other exceptions, use default behavior

112

return Override.CONTINUE_EVICT;

113

}

114

}

115

116

// Configure in HikariConfig

117

HikariConfig config = new HikariConfig();

118

config.setExceptionOverrideClassName("com.example.CustomExceptionOverride");

119

```

120

121

### Thread Factory Customization

122

123

Support for custom thread factories to control thread creation for HikariCP's internal operations.

124

125

```java { .api }

126

// In HikariConfig class

127

/**

128

* Set custom ThreadFactory for internal thread creation

129

* @param threadFactory Custom ThreadFactory implementation

130

*/

131

public void setThreadFactory(ThreadFactory threadFactory);

132

133

/**

134

* Get the configured ThreadFactory

135

* @return Current ThreadFactory or null if using default

136

*/

137

public ThreadFactory getThreadFactory();

138

```

139

140

**Custom Thread Factory Example:**

141

142

```java

143

import java.util.concurrent.ThreadFactory;

144

import java.util.concurrent.atomic.AtomicInteger;

145

146

public class CustomHikariThreadFactory implements ThreadFactory {

147

private final AtomicInteger threadNumber = new AtomicInteger(1);

148

private final String namePrefix;

149

150

public CustomHikariThreadFactory(String poolName) {

151

this.namePrefix = "HikariCP-" + poolName + "-thread-";

152

}

153

154

@Override

155

public Thread newThread(Runnable r) {

156

Thread thread = new Thread(r, namePrefix + threadNumber.getAndIncrement());

157

thread.setDaemon(true);

158

thread.setPriority(Thread.NORM_PRIORITY);

159

return thread;

160

}

161

}

162

163

// Configure in HikariConfig

164

HikariConfig config = new HikariConfig();

165

config.setThreadFactory(new CustomHikariThreadFactory("MyPool"));

166

```

167

168

### Scheduled Executor Customization

169

170

Support for custom ScheduledExecutorService for HikariCP's internal scheduled tasks.

171

172

```java { .api }

173

// In HikariConfig class

174

/**

175

* Set custom ScheduledExecutorService for internal scheduled tasks

176

* @param executor Custom ScheduledExecutorService implementation

177

*/

178

public void setScheduledExecutor(ScheduledExecutorService executor);

179

180

/**

181

* Get the configured ScheduledExecutorService

182

* @return Current ScheduledExecutorService or null if using default

183

*/

184

public ScheduledExecutorService getScheduledExecutor();

185

```

186

187

**Custom Scheduled Executor Example:**

188

189

```java

190

import java.util.concurrent.Executors;

191

import java.util.concurrent.ScheduledExecutorService;

192

193

// Create custom scheduled executor

194

ScheduledExecutorService customExecutor = Executors.newScheduledThreadPool(2,

195

new CustomHikariThreadFactory("ScheduledTasks"));

196

197

// Configure in HikariConfig

198

HikariConfig config = new HikariConfig();

199

config.setScheduledExecutor(customExecutor);

200

201

// Remember to shutdown executor when no longer needed

202

// customExecutor.shutdown();

203

```

204

205

### Connection Initialization SQL

206

207

Execute custom SQL statements when new connections are created, useful for session-level configuration.

208

209

```java { .api }

210

// In HikariConfig class

211

/**

212

* Set SQL statement to execute when connections are created

213

* @param sql SQL statement to execute on new connections

214

*/

215

public void setConnectionInitSql(String sql);

216

217

/**

218

* Get the connection initialization SQL

219

* @return SQL statement executed on new connections

220

*/

221

public String getConnectionInitSql();

222

```

223

224

**Connection Initialization Example:**

225

226

```java

227

HikariConfig config = new HikariConfig();

228

config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");

229

config.setUsername("user");

230

config.setPassword("password");

231

232

// Set timezone and other session variables for new connections

233

config.setConnectionInitSql("SET time_zone = '+00:00'; SET autocommit = 1;");

234

235

HikariDataSource dataSource = new HikariDataSource(config);

236

```

237

238

### Health Check Properties

239

240

Configure health check properties for connection validation and monitoring integration.

241

242

```java { .api }

243

// In HikariConfig class

244

/**

245

* Set health check registry for monitoring integration

246

* @param healthCheckRegistry Health check registry instance

247

*/

248

public void setHealthCheckRegistry(Object healthCheckRegistry);

249

250

/**

251

* Get the health check registry

252

* @return Health check registry instance

253

*/

254

public Object getHealthCheckRegistry();

255

256

/**

257

* Set health check properties

258

* @param healthCheckProperties Properties for health check configuration

259

*/

260

public void setHealthCheckProperties(Properties healthCheckProperties);

261

262

/**

263

* Get health check properties

264

* @return Health check properties

265

*/

266

public Properties getHealthCheckProperties();

267

268

/**

269

* Add individual health check property

270

* @param key Property key

271

* @param value Property value

272

*/

273

public void addHealthCheckProperty(String key, String value);

274

```

275

276

**Health Check Configuration Example:**

277

278

```java

279

import com.codahale.metrics.health.HealthCheckRegistry;

280

281

// Create health check registry

282

HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();

283

284

HikariConfig config = new HikariConfig();

285

config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");

286

config.setUsername("user");

287

config.setPassword("password");

288

289

// Configure health checks

290

config.setHealthCheckRegistry(healthCheckRegistry);

291

config.addHealthCheckProperty("connectivityCheck", "true");

292

config.addHealthCheckProperty("expected99thPercentile", "10");

293

294

HikariDataSource dataSource = new HikariDataSource(config);

295

```

296

297

### Pool Suspension and Resumption

298

299

Advanced pool control for maintenance operations and graceful shutdowns.

300

301

```java { .api }

302

// In HikariConfig class

303

/**

304

* Allow pool suspension for maintenance operations

305

* @param isAllowPoolSuspension Whether to allow pool suspension

306

*/

307

public void setAllowPoolSuspension(boolean isAllowPoolSuspension);

308

309

/**

310

* Check if pool suspension is allowed

311

* @return true if pool suspension is allowed

312

*/

313

public boolean isAllowPoolSuspension();

314

```

315

316

**Pool Suspension Example:**

317

318

```java

319

HikariConfig config = new HikariConfig();

320

config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");

321

config.setUsername("user");

322

config.setPassword("password");

323

config.setAllowPoolSuspension(true); // Enable suspension capability

324

325

HikariDataSource dataSource = new HikariDataSource(config);

326

327

// Get pool management bean

328

HikariPoolMXBean poolBean = dataSource.getHikariPoolMXBean();

329

330

// Suspend pool for maintenance

331

poolBean.suspendPool();

332

333

// Perform maintenance operations

334

// ...

335

336

// Resume pool operations

337

poolBean.resumePool();

338

```

339

340

### Transaction Isolation Levels

341

342

Configure default transaction isolation level for connections.

343

344

```java { .api }

345

// In HikariConfig class

346

/**

347

* Set default transaction isolation level

348

* @param transactionIsolation Transaction isolation level name

349

*/

350

public void setTransactionIsolation(String transactionIsolation);

351

352

/**

353

* Get the transaction isolation level

354

* @return Transaction isolation level name

355

*/

356

public String getTransactionIsolation();

357

```

358

359

**Transaction Isolation Example:**

360

361

```java

362

HikariConfig config = new HikariConfig();

363

config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");

364

config.setUsername("user");

365

config.setPassword("password");

366

367

// Set transaction isolation level

368

config.setTransactionIsolation("TRANSACTION_READ_COMMITTED");

369

// Other options: TRANSACTION_READ_UNCOMMITTED, TRANSACTION_REPEATABLE_READ, TRANSACTION_SERIALIZABLE

370

371

HikariDataSource dataSource = new HikariDataSource(config);

372

```

373

374

These advanced features provide fine-grained control over HikariCP behavior for specialized deployment scenarios and enterprise requirements. Most applications will not need these features, but they provide powerful customization options when required.