-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectionPool.java
More file actions
1099 lines (926 loc) · 45.9 KB
/
ConnectionPool.java
File metadata and controls
1099 lines (926 loc) · 45.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package javaxt.sql;
import java.util.Map;
import java.util.HashMap;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.sql.ConnectionEvent;
import javax.sql.ConnectionEventListener;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.PooledConnection;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
//******************************************************************************
//** ConnectionPool
//******************************************************************************
/**
* A lightweight, high-performance JDBC connection pool manager with health
* monitoring, validation caching, and lock-free concurrent connection
* management.
*
******************************************************************************/
public class ConnectionPool {
private ConnectionPoolDataSource dataSource;
private int maxConnections;
private int minConnections;
private long timeoutMs;
private PrintWriter logWriter;
private final AtomicInteger totalConnections = new AtomicInteger(0); // Lock-free connection counting
private PoolConnectionEventListener poolConnectionEventListener;
// Health monitoring and validation
private long connectionIdleTimeoutMs;
private long connectionMaxAgeMs;
private String validationQuery;
private int validationTimeout;
private ScheduledExecutorService healthCheckExecutor;
private ScheduledFuture<?> healthCheckTask;
// Thread-safe counters and flags
private final AtomicInteger activeConnections = new AtomicInteger(0);
private final AtomicBoolean isDisposed = new AtomicBoolean(false);
private final AtomicBoolean doPurgeConnection = new AtomicBoolean(false);
// Thread-safe connection storage
private final ConcurrentLinkedQueue<PooledConnectionWrapper> recycledConnections = new ConcurrentLinkedQueue<>();
private final ConcurrentHashMap<PooledConnection, PooledConnectionWrapper> connectionWrappers = new ConcurrentHashMap<>();
private volatile PooledConnection connectionInTransition;
// Validation caching for performance optimization
private final ConcurrentHashMap<PooledConnection, Long> validationCache = new ConcurrentHashMap<>();
private static final long VALIDATION_CACHE_TTL = 30000; // 30 seconds
private Database database;
//**************************************************************************
//** Constructor
//**************************************************************************
public ConnectionPool(Database database, int maxConnections) throws SQLException {
this(database, maxConnections, null);
}
//**************************************************************************
//** Constructor
//**************************************************************************
public ConnectionPool(Database database, int maxConnections, int timeout) throws SQLException{
this(database, maxConnections, new HashMap<String, Object>() {{
put("timeout", timeout);
}});
}
//**************************************************************************
//** Constructor
//**************************************************************************
/** Used to instantiate the ConnectionPool using with a javaxt.sql.Database
* @param database javaxt.sql.Database with database connection information
* including a valid getConnectionPoolDataSource() response. The database
* object provides additional run-time query optimizations (e.g. connection
* metadata).
* @param maxConnections Maximum number of database connections for the
* connection pool.
* @param options Additional pool configuration options including:
* <ul>
* <li>timeout: The maximum time to wait for a free connection, in seconds. Default is 20 seconds.</li>
* <li>idleTimeout: Connection idle timeout in seconds. Default is 300 seconds (5 minutes).</li>
* <li>maxAge: Maximum connection age in seconds. Default is 1800 seconds (30 minutes).</li>
* <li>validationQuery: Query to validate connections. Default is "SELECT 1".</li>
* <li>validationTimeout: Interval used to execute validation queries. Default is 5 seconds.</li>
* </ul>
*/
public ConnectionPool(Database database, int maxConnections, Map<String, Object> options) throws SQLException {
if (database==null) throw new IllegalArgumentException("Database is required");
this.database = database;
init(database.getConnectionPoolDataSource(), maxConnections, options);
}
//**************************************************************************
//** Constructor
//**************************************************************************
public ConnectionPool(ConnectionPoolDataSource dataSource, int maxConnections) {
init(dataSource, maxConnections, null);
}
//**************************************************************************
//** Constructor
//**************************************************************************
public ConnectionPool(ConnectionPoolDataSource dataSource, int maxConnections, Integer timeout) {
init(dataSource, maxConnections, new HashMap<String, Object>() {{
put("timeout", timeout);
}});
}
//**************************************************************************
//** Constructor
//**************************************************************************
public ConnectionPool(ConnectionPoolDataSource dataSource, int maxConnections, Map<String, Object> options) throws SQLException {
init(dataSource, maxConnections, options);
}
//**************************************************************************
//** getConnection
//**************************************************************************
/** Retrieves a connection from the connection pool. If all the connections
* are in use, the method waits until a connection becomes available or
* <code>timeout</code> seconds elapsed. When the application is finished
* using the connection, it must be closed in order to return it to the
* pool.
*/
public Connection getConnection() throws SQLException {
long time = System.currentTimeMillis();
long timeoutTime = time + timeoutMs;
int triesWithoutDelay = getInactiveConnections() + 1;
while (true) {
Connection conn = getConnection(time, timeoutTime);
if (conn != null) {
return conn;
}
triesWithoutDelay--;
if (triesWithoutDelay <= 0) {
triesWithoutDelay = 0;
try {
// Intentional sleep to avoid busy waiting when no connections are available
Thread.sleep(250);
}
catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting for a valid database connection.", e);
}
}
time = System.currentTimeMillis();
if (time >= timeoutTime) {
throw new TimeoutException("Timeout while waiting for a valid database connection.");
}
}
}
//**************************************************************************
//** getActiveConnections
//**************************************************************************
/** Returns the number of active (open) connections of this pool.
*
* <p>This is the number of <code>Connection</code> objects that have been
* issued by {@link #getConnection()}, for which <code>Connection.close()</code>
* has not yet been called.</p>
*/
public int getActiveConnections() {
return activeConnections.get();
}
//**************************************************************************
//** getInactiveConnections
//**************************************************************************
/** Returns the number of inactive (unused) connections in this pool.
*
* <p>This is the number of internally kept recycled connections,
* for which <code>Connection.close()</code> has been called and which
* have not yet been reused.</p>
*/
public int getInactiveConnections() {
return recycledConnections.size();
}
//**************************************************************************
//** getMaxConnections
//**************************************************************************
/** Returns the configured maximum number of connections in the pool.
*/
public int getMaxConnections(){
return maxConnections;
}
//**************************************************************************
//** getConnectionPoolDataSource
//**************************************************************************
/** Returns the ConnectionPoolDataSource backing this connection pool.
*/
public ConnectionPoolDataSource getConnectionPoolDataSource(){
return dataSource;
}
//**************************************************************************
//** getTimeout
//**************************************************************************
/** Returns the maximum time to wait for a free connection, in seconds.
*/
public int getTimeout(){
return Math.round(timeoutMs/1000);
}
//**************************************************************************
//** getConnectionIdleTimeout
//**************************************************************************
/** Returns the connection idle timeout in seconds. Connections that remain
* unused in the pool for more than the idle timeout are automatically
* removed. This prevents accumulation of stale connections that may have
* been closed by the database server. Note that this only affects
* connections sitting idle in the pool, not active connections being used
* by your application.
*/
public int getConnectionIdleTimeout() {
return Math.round(connectionIdleTimeoutMs/1000);
}
//**************************************************************************
//** getConnectionIdleTimeout
//**************************************************************************
/** Returns the maximum connection age in seconds.
*/
public long getConnectionMaxAge() {
return Math.round(connectionMaxAgeMs/1000);
}
//**************************************************************************
//** getValidationQuery
//**************************************************************************
/** Returns the validation query used to periodically test connections in
* the pool.
*/
public String getValidationQuery() {
return validationQuery;
}
//**************************************************************************
//** getValidationTimeout
//**************************************************************************
/** Returns the interval used to execute validation queries in seconds.
*/
public int getValidationTimeout() {
return validationTimeout;
}
//**************************************************************************
//** close
//**************************************************************************
/** Closes all unused pooled connections and shuts down the connection pool.
* After calling this method, clients can no longer get new connections via
* getConnection().
*/
public void close() throws SQLException {
if (!isDisposed.compareAndSet(false, true)) {
return; // Already disposed
}
stopHealthMonitoring();
// Use disposeConnection to properly handle the totalConnectionCount decrement
PooledConnectionWrapper wrapper;
while ((wrapper = recycledConnections.poll()) != null) {
disposeConnection(wrapper.pooledConnection);
}
connectionWrappers.clear();
}
//**************************************************************************
//** isClosed
//**************************************************************************
/** Returns true if the connection pool has been closed.
*/
public boolean isClosed() {
return isDisposed.get();
}
//**************************************************************************
//** init
//**************************************************************************
private void init(ConnectionPoolDataSource dataSource, int maxConnections, Map<String, Object> options) {
if (dataSource==null) throw new IllegalArgumentException("dataSource is required");
if (maxConnections<1) throw new IllegalArgumentException("Invalid maxConnections");
if (options==null) options = new HashMap<>();
Integer timeout = new Value(options.get("timeout")).toInteger();
if (timeout==null || timeout <= 0) timeout = 20; // 20 seconds default
Integer idleTimeout = new Value(options.get("idleTimeout")).toInteger();
if (idleTimeout==null || idleTimeout <= 0) idleTimeout = 300; // 5 minutes default
Integer maxAge = new Value(options.get("maxAge")).toInteger();
if (maxAge==null || maxAge <= 0) maxAge = 1800; // 30 minutes default
Integer validationTimeout = new Value(options.get("validationTimeout")).toInteger();
if (validationTimeout==null || validationTimeout <= 0) validationTimeout = 5; // 5 seconds
String validationQuery = new Value(options.get("validationQuery")).toString();
if (validationQuery == null || validationQuery.trim().isEmpty()) {
validationQuery = "SELECT 1";
}
else{
validationQuery = validationQuery.trim();
}
this.dataSource = dataSource;
this.maxConnections = maxConnections;
this.minConnections = (int) Math.round(Math.max(((long)maxConnections)*0.2, 1.0));
this.timeoutMs = timeout * 1000L;
this.connectionIdleTimeoutMs = idleTimeout * 1000L;
this.connectionMaxAgeMs = maxAge * 1000L;
this.validationQuery = validationQuery;
this.validationTimeout = validationTimeout;
// Initialize atomic counter for lock-free connection management
this.totalConnections.set(0);
try { logWriter = dataSource.getLogWriter(); }
catch (SQLException e) {}
poolConnectionEventListener = new PoolConnectionEventListener();
startHealthMonitoring();
}
//**************************************************************************
//** getConnection
//**************************************************************************
private Connection getConnection(long time, long timeoutTime) {
long rtime = Math.max(1, timeoutTime - time);
Connection connection;
try {
connection = acquireConnection(rtime);
}
catch (SQLException e) {
return null;
}
// Calculate remaining time for validation
rtime = timeoutTime - System.currentTimeMillis();
int rtimeSecs = Math.max(1, (int)((rtime + 999) / 1000));
// Validate using the underlying raw connection
java.sql.Connection rawConn = connection.getConnection();
try {
if (rawConn.isValid(rtimeSecs)) {
return connection;
}
}
catch (SQLException e) {
log("isValid() failed: " + e.getMessage());
// This Exception should never occur. If it nevertheless occurs, it's because of an error in the
// JDBC driver which we ignore and assume that the connection is not valid.
}
// When isValid() returns false, the JDBC driver should have already called connectionErrorOccurred()
// and the PooledConnection has been removed from the pool, i.e. the PooledConnection will
// not be added to recycledConnections when Connection.close() is called.
// But to be sure that this works even with a faulty JDBC driver, we call purgeConnection().
purgeConnection(rawConn);
return null;
}
//**************************************************************************
//** acquireConnection
//**************************************************************************
private Connection acquireConnection(long timeoutMs) throws SQLException {
if (isDisposed.get()) {
throw new IllegalStateException("Connection pool has been disposed.");
}
long startTime = System.currentTimeMillis();
long timeoutTime = startTime + timeoutMs;
while (System.currentTimeMillis() < timeoutTime) {
// First, try to get a recycled connection
Connection recycledConn = getRecycledConnection();
if (recycledConn != null) {
return recycledConn;
}
// No recycled connection available, try to create a new one
// Use atomic counter for lock-free connection limit control
int currentTotal = totalConnections.get();
if (currentTotal < maxConnections) {
if (totalConnections.compareAndSet(currentTotal, currentTotal + 1)) {
try {
Connection conn = createNewConnection();
if (conn != null) {
return conn;
} else {
// Connection creation failed, decrement counter
totalConnections.decrementAndGet();
}
} catch (SQLException e) {
// Connection creation failed, decrement counter
totalConnections.decrementAndGet();
// Continue to next iteration to try again
}
}
}
// If we couldn't create a connection, wait a bit and try again
try {
Thread.sleep(10);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted while waiting for a database connection.", e);
}
}
throw new TimeoutException();
}
//**************************************************************************
//** getRecycledConnection
//**************************************************************************
private Connection getRecycledConnection() throws SQLException {
PooledConnectionWrapper wrapper = recycledConnections.poll();
if (wrapper == null) {
return null; // No recycled connections available
}
PooledConnection pconn = wrapper.pooledConnection;
// Check if the connection was recently recycled (< 5 seconds)
boolean connectionIsStale = (System.currentTimeMillis() - wrapper.lastUsedTime) > 5000;
// Skip validation for very recently recycled connections (< 5 seconds)
// This dramatically improves performance for high-frequency connection reuse scenarios
// Also skip validation for warm-up connections (they're brand new)
if (!wrapper.isWarmup && connectionIsStale) {
// Standard validation path for older connections
boolean needsValidation = wrapper.isExpired(connectionMaxAgeMs) ||
wrapper.isIdle(connectionIdleTimeoutMs) ||
!isRecentlyValidated(pconn);
if (needsValidation && !validateConnection(pconn)) {
// Connection is invalid, dispose it properly
doPurgeConnection.set(true);
try {
pconn.removeConnectionEventListener(poolConnectionEventListener);
pconn.close();
} catch (SQLException e) {
// Ignore close errors for invalid connections
} finally {
doPurgeConnection.set(false);
}
connectionWrappers.remove(pconn);
totalConnections.decrementAndGet();
return null; // Try another recycled connection or create new one
}
}
try {
connectionInTransition = pconn;
activeConnections.incrementAndGet(); // Increment before getting connection
// Get a fresh logical connection from the PooledConnection
java.sql.Connection rawConn = pconn.getConnection();
// Re-open the javaxt.sql.Connection wrapper with the fresh logical connection
// This updates the underlying connection reference without creating a new wrapper object
wrapper.connection.open(rawConn, database);
// Connection successfully acquired! Now update the wrapper state
// IMPORTANT: Only update wrapper and map AFTER successfully acquiring the connection
// This prevents race conditions where the wrapper state changes before the connection is ready
PooledConnectionWrapper updatedWrapper = wrapper.markUsed();
connectionWrappers.put(pconn, updatedWrapper);
return updatedWrapper.connection; // Return reused wrapper with fresh connection
} catch (SQLException e) {
connectionInTransition = null;
// Failed to acquire connection
// Decrement the activeConnections counter we just incremented
activeConnections.decrementAndGet();
// IMPORTANT: Set doPurgeConnection BEFORE closing to prevent double-decrement
// This ensures that if pconn.close() triggers connectionClosed event,
// it will call disposeConnection() instead of recycleConnection()
doPurgeConnection.set(true);
try {
// Don't remove the wrapper if it's a warmup connection - it needs to stay in the map
// Only remove if it was updated to non-warmup
// Actually, remove it to be safe - disposeConnection will handle it
connectionWrappers.remove(pconn);
pconn.removeConnectionEventListener(poolConnectionEventListener);
pconn.close();
} catch (SQLException ex) {
// Ignore close errors for failed connections
} finally {
doPurgeConnection.set(false);
totalConnections.decrementAndGet();
}
return null;
} finally {
connectionInTransition = null;
}
}
//**************************************************************************
//** createNewConnection
//**************************************************************************
private Connection createNewConnection() throws SQLException {
PooledConnection pconn;
try {
pconn = dataSource.getPooledConnection();
pconn.addConnectionEventListener(poolConnectionEventListener);
Connection connection;
try {
connectionInTransition = pconn;
activeConnections.incrementAndGet(); // Increment before getConnection() to ensure it's always counted
// Get raw connection and wrap it ONCE
java.sql.Connection rawConn = pconn.getConnection();
connection = new Connection();
connection.open(rawConn, database);
// Store the pre-wrapped connection for reuse
connectionWrappers.put(pconn, new PooledConnectionWrapper(connection, pconn, false));
// totalConnections was already incremented in acquireConnection
return connection;
} catch (SQLException e) {
connectionInTransition = null;
// Connection creation failed, decrement the activeConnections counter we just incremented
activeConnections.decrementAndGet();
// Connection creation failed, clean up
connectionWrappers.remove(pconn);
doPurgeConnection.set(true);
try {
pconn.removeConnectionEventListener(poolConnectionEventListener);
pconn.close();
} catch (SQLException ex) {
// Ignore close errors for failed connections
} finally {
doPurgeConnection.set(false);
totalConnections.decrementAndGet();
}
throw e;
} finally {
connectionInTransition = null;
}
} catch (SQLException e) {
throw e;
}
}
//**************************************************************************
//** startHealthMonitoring
//**************************************************************************
/** Starts the background health monitoring thread.
*/
private void startHealthMonitoring() {
healthCheckExecutor = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "ConnectionPool-HealthCheck");
t.setDaemon(true);
return t;
});
// Run health check every 30 seconds
healthCheckTask = healthCheckExecutor.scheduleWithFixedDelay(
this::performHealthCheck, 30, 30, TimeUnit.SECONDS);
}
//**************************************************************************
//** stopHealthMonitoring
//**************************************************************************
/** Stops the health monitoring thread.
*/
private void stopHealthMonitoring() {
if (healthCheckTask != null) {
healthCheckTask.cancel(false);
healthCheckTask = null;
}
if (healthCheckExecutor != null) {
healthCheckExecutor.shutdown();
try {
if (!healthCheckExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
healthCheckExecutor.shutdownNow();
log("Health monitoring thread did not terminate gracefully");
}
} catch (InterruptedException e) {
healthCheckExecutor.shutdownNow();
Thread.currentThread().interrupt();
}
healthCheckExecutor = null;
}
}
//**************************************************************************
//** performHealthCheck
//**************************************************************************
/** Performs health check on idle connections.
*/
private void performHealthCheck() {
try {
log("Health check started");
int removedCount = 0;
long now = System.currentTimeMillis();
// Check for idle and expired connections
log("Checking " + recycledConnections.size() + " recycled connections for idle/expired");
// Drain connections to temporary list to avoid concurrent modification
java.util.List<PooledConnectionWrapper> toCheck = new java.util.ArrayList<>();
PooledConnectionWrapper wrapper;
while ((wrapper = recycledConnections.poll()) != null) {
toCheck.add(wrapper);
}
// Process connections and re-add valid ones
for (PooledConnectionWrapper w : toCheck) {
if (w.isIdle(connectionIdleTimeoutMs) || w.isExpired(connectionMaxAgeMs)) {
disposeConnection(w.pooledConnection);
removedCount++;
log("Removed " + (w.isExpired(connectionMaxAgeMs) ? "expired" : "idle") +
" connection from pool. Age: " + (now - w.createdTime) + "ms");
} else {
// Re-add valid connection back to the queue
recycledConnections.offer(w);
}
}
if (removedCount > 0) {
log("Health check completed: removed " + removedCount + " connections");
}
// Log pool statistics periodically
PoolStatistics stats = getPoolStatistics();
log("Pool stats - Active: " + stats.activeConnections +
", Recycled: " + stats.recycledConnections +
", Available permits: " + stats.availablePermits +
", Max: " + stats.maxConnections +
", Min: " + stats.minConnections +
", Total: " + stats.totalConnections);
// Ensure at least minConnections are available (warmed) in the pool
int currentRecycled = recycledConnections.size();
int currentActive = activeConnections.get();
int total = currentActive + currentRecycled;
if (currentRecycled < minConnections && total < maxConnections && !isDisposed.get()) {
log("Pool warm-up: ensuring minimum " + minConnections + " connections available");
int maxAttempts = 3; // Limit attempts to prevent infinite loops
int attempts = 0;
while (currentRecycled < minConnections && total < maxConnections && !isDisposed.get() && attempts < maxAttempts) {
attempts++;
// Try to increment totalConnections for the warm-up connection
int currentTotal = totalConnections.get();
if (currentTotal >= maxConnections) {
log("Maximum connections reached for pool warm-up");
break;
}
if (!totalConnections.compareAndSet(currentTotal, currentTotal + 1)) {
continue; // Try again if CAS failed
}
PooledConnection pconn = null;
try {
pconn = dataSource.getPooledConnection();
pconn.addConnectionEventListener(poolConnectionEventListener);
if (validateConnection(pconn)) {
// Create unopened wrapper for warm-up
// The wrapper will be opened when first acquired from the pool
Connection connection = new Connection();
PooledConnectionWrapper w = new PooledConnectionWrapper(connection, pconn, true); // Mark as warmup
connectionWrappers.put(pconn, w);
// Add directly to recycled queue (skip the active state for warm-up)
recycledConnections.offer(w);
currentRecycled++;
total = currentActive + currentRecycled;
log("Pool warm-up: added connection " + currentRecycled + "/" + minConnections);
} else {
// If validation fails, dispose the connection and decrement counter
disposeConnection(pconn);
pconn = null; // Ensure pconn is null so finally block doesn't try to close it again
}
} catch (SQLException e) {
log("Failed to create or validate connection during warm-up: " + e.getMessage());
if (pconn != null) {
disposeConnection(pconn); // Dispose and decrement counter
} else {
totalConnections.decrementAndGet(); // Decrement counter if connection creation failed before pconn was assigned
}
}
}
if (attempts >= maxAttempts) {
log("Pool warm-up: reached maximum attempts (" + maxAttempts + ")");
}
}
} catch (Exception e) {
log("Error during health check: " + e.getMessage());
}
}
//**************************************************************************
//** isRecentlyValidated
//**************************************************************************
/** Validates a connection using the configured validation query.
* This method is completely isolated from the pool lifecycle to prevent race conditions.
*/
private boolean isRecentlyValidated(PooledConnection pooledConnection) {
if (validationQuery == null || validationQuery.trim().isEmpty()) {
return true; // No validation query configured, consider it valid
}
Long lastValidated = validationCache.get(pooledConnection);
if (lastValidated == null) {
return false; // Never validated
}
long now = System.currentTimeMillis();
return (now - lastValidated) < VALIDATION_CACHE_TTL;
}
//**************************************************************************
//** validateConnection
//**************************************************************************
private boolean validateConnection(PooledConnection pooledConnection) {
if (validationQuery == null || validationQuery.trim().isEmpty()) {
return true;
}
// Check validation cache first
Long lastValidated = validationCache.get(pooledConnection);
long now = System.currentTimeMillis();
if (lastValidated != null && (now - lastValidated) < VALIDATION_CACHE_TTL) {
return true; // Recently validated, skip actual validation
}
// TODO: Implement a safer validation mechanism that doesn't interfere with driver pooling
return true;
}
//**************************************************************************
//** purgeConnection
//**************************************************************************
/** Purges the PooledConnection associated with the passed Connection from
* the connection pool.
*/
private void purgeConnection(java.sql.Connection conn) {
doPurgeConnection.set(true);
try {
// Setting doPurgeConnection flag ensures that when connectionClosed() fires,
// recycleConnection() will call disposeConnection() instead of recycling the connection.
conn.close();
} catch (SQLException e) {
log("Error closing connection during purge: " + e.getMessage());
} finally {
doPurgeConnection.set(false);
}
}
//**************************************************************************
//** recycleConnection
//**************************************************************************
private void recycleConnection (PooledConnection pconn) {
if (isDisposed.get() || doPurgeConnection.get()) {
disposeConnection(pconn);
return;
}
// Check if this connection is currently being processed to prevent duplicate processing
if (pconn == connectionInTransition) {
log("Warning: Ignoring recycle request for connection in transition - potential leak risk");
return;
}
// Get the existing wrapper
PooledConnectionWrapper wrapper = connectionWrappers.get(pconn);
// Check if this connection is already in the recycled queue (double-close protection)
if (wrapper != null) {
for (PooledConnectionWrapper w : recycledConnections) {
if (w.pooledConnection == pconn) {
log("Warning: Connection already recycled, ignoring duplicate close");
return;
}
}
// Additional safety check: verify the wrapper's connection is actually closed
// If the javaxt.sql.Connection wrapper is still open, this indicates a problem
if (wrapper.connection != null && wrapper.connection.isOpen()) {
log("Warning: Recycle called but javaxt.sql.Connection wrapper is still open - disposing instead");
disposeConnection(pconn);
return;
}
}
// Use atomic decrement to avoid TOCTOU race condition
int prev = activeConnections.decrementAndGet();
if (prev < 0) {
// This is a double-close - the connection was already recycled
// Don't restore the counter; instead increment it back and ignore this duplicate close
activeConnections.incrementAndGet();
String wrapperInfo = wrapper != null ?
"(isWarmup=" + wrapper.isWarmup + ", created=" + wrapper.createdTime + ", lastUsed=" + wrapper.lastUsedTime + ")" :
"(wrapper=null)";
log("WARNING: Detected double-close (activeConnections went negative). " +
"Ignoring duplicate recycle. This indicates the same javaxt.sql.Connection object was closed twice. " +
"wrapper=" + wrapperInfo);
// Don't process this recycle - the connection was already recycled on the first close
return;
}
// Get the existing wrapper and update its usage time
if (wrapper != null) {
// Update the wrapper with current usage time and add to recycled connections
// The javaxt.sql.Connection wrapper is reused - no new object creation!
wrapper = wrapper.markUsed();
recycledConnections.offer(wrapper);
}
else {
// This shouldn't happen in normal operation - log a warning
log("Warning: Wrapper not found for PooledConnection during recycle");
}
// Connection successfully recycled
// Note: totalConnections remains unchanged during recycling since the connection
// is just moving from active to recycled state, not being disposed
}
//**************************************************************************
//** disposeConnection
//**************************************************************************
private void disposeConnection (PooledConnection pconn) {
pconn.removeConnectionEventListener(poolConnectionEventListener);
// Use connectionWrappers.remove() return value as a guard to prevent double disposal
// Only proceed with disposal if this connection was actually managed by the pool
PooledConnectionWrapper removedWrapper = connectionWrappers.remove(pconn);
if (removedWrapper == null) {
// Connection was not managed by the pool, nothing to dispose
return;
}
validationCache.remove(pconn);
// Try to remove from recycled connections
boolean foundInRecycled = false;
for (PooledConnectionWrapper wrapper : recycledConnections) {
if (wrapper.pooledConnection == pconn) {
if (recycledConnections.remove(wrapper)) {
foundInRecycled = true;
}
break;
}
}
// If not found in recycled connections and not currently in transition,
// and not being purged (validation connections), we assume that the connection was active
if (!foundInRecycled && pconn != connectionInTransition && !doPurgeConnection.get()) {
// Use atomic decrement to avoid race condition
int prev = activeConnections.decrementAndGet();
if (prev < 0) {
// Connection was never counted as active, restore counter
activeConnections.incrementAndGet();
}
}
// Only decrement totalConnections when disposing a connection (not recycling)
// This ensures that the total connection count is properly managed
if (!foundInRecycled) {
totalConnections.decrementAndGet();
}
try {
pconn.close();
}
catch (SQLException e) {
log("Error while closing database connection: "+e.toString());
}
assertInnerState();
}
//**************************************************************************
//** log
//**************************************************************************
private void log(String msg) {
if (true) return;
String s = "ConnectionPool: "+msg;
try {
if (logWriter == null) {
if (msg.startsWith("WARNING") || msg.startsWith("Error")) {
System.err.println(s);
}
}
else {
logWriter.println(s);
}
}
catch (Exception e) {}
}
//**************************************************************************
//** assertInnerState
//**************************************************************************
private void assertInnerState() {
int active = activeConnections.get();
int total = totalConnections.get();
if (active < 0) {
throw new AssertionError("Active connections count is negative: " + active);
}
if (total < 0) {
throw new AssertionError("Total connections count is negative: " + total);
}
// Relaxed assertion: allow temporary overshoot due to lock-free design timing windows
// Only fail if we're significantly over the limit (more than 10% tolerance)
if (total > maxConnections + Math.max(1, maxConnections / 10)) {
throw new AssertionError("Total connections significantly exceed maximum: total=" + total +
", max=" + maxConnections + ", tolerance=" + Math.max(1, maxConnections / 10));
}
}
//**************************************************************************
//** PoolConnectionEventListener Class
//**************************************************************************
private class PoolConnectionEventListener implements ConnectionEventListener {
@Override
public void connectionClosed (ConnectionEvent event) {
PooledConnection pconn = (PooledConnection)event.getSource();
recycleConnection(pconn);
}
@Override
public void connectionErrorOccurred (ConnectionEvent event) {
PooledConnection pconn = (PooledConnection)event.getSource();
disposeConnection(pconn);
}
}
//**************************************************************************
//** PooledConnectionWrapper Class
//**************************************************************************
/** Wrapper class to track connection metadata