Skip to content

Commit 504cb5a

Browse files
committed
fix(bigquery-jdbc): fix physical connection sharing and concurrent checkout in PooledConnectionDataSource
- Open a dedicated physical BigQueryConnection on cache misses and recycle idle physical connections into fresh BigQueryPooledConnection holders while retiring prior holders. - Separate PooledConnectionDataSource's internal pool listener from public ConnectionEventListener slots, make external listener detachment sticky across removeConnectionEventListener -> close(), and preserve overflow teardown for standalone PooledConnectionListener instances. - Use LIFO (addFirst/pollFirst) idle reuse in PooledConnectionListener, close excess driver-owned idle connections at capacity, and clarify ConnectionPoolSize and ListenerPoolSize in docs/USER_GUIDE.md.
1 parent 622760a commit 504cb5a

7 files changed

Lines changed: 946 additions & 154 deletions

File tree

‎java-bigquery-jdbc/docs/USER_GUIDE.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -272,8 +272,8 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443"
272272
| `RetryInitialDelay` | `0` | Initial delay (in seconds) before executing the first retry attempt. |
273273
| `RetryMaxDelay` | `0` | Maximum delay limit (in seconds) between retry attempts. |
274274
| `MetaDataFetchThreadCount` | `32` | Thread pool size used to parallelize `DatabaseMetaData` catalog RPC calls. |
275-
| `ConnectionPoolSize` | `10` | Maximum size of the internal connection pool when connection pooling is enabled. |
276-
| `ListenerPoolSize` | `10` | Maximum size of the listener thread pool when connection pooling is enabled. |
275+
| `ConnectionPoolSize` | `10` | Maximum number of idle physical connections retained in `PooledConnectionDataSource`'s built-in pool (`0` = unbounded). Latched from the first physical connection checkout; changing it on the same `PooledConnectionDataSource` afterward has no effect. |
276+
| `ListenerPoolSize` | `10` | Maximum number of `ConnectionEventListener` instances that can be registered on a single `PooledConnection` (`0` = unbounded). |
277277
| `RequestReason` | `null` | Reason string passed in the `x-goog-request-reason` HTTP header for auditing. |
278278
279279
### OpenTelemetry & Cloud Observability Exporters

‎java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryPooledConnection.java‎

Lines changed: 117 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ class BigQueryPooledConnection implements PooledConnection {
5353
enum State {
5454
IDLE,
5555
IN_USE,
56+
RETIRED,
5657
CLOSED
5758
}
5859

@@ -64,6 +65,9 @@ enum State {
6465
private final List<ConnectionEventListener> listeners;
6566
private final Object physicalLock = new Object();
6667
private final Object stateLock = new Object();
68+
private PooledConnectionListener internalPoolListener;
69+
private boolean detachedFromInternalPool = false;
70+
private boolean nonPoolListenerAttached = false;
6771
private PooledConnectionInvocationHandler activeHandle;
6872
private PooledConnectionInvocationHandler resettingHandle;
6973
private volatile State state = State.IDLE;
@@ -96,14 +100,76 @@ boolean inUse() {
96100
return this.state == State.IN_USE;
97101
}
98102

103+
boolean isAvailableForPool() {
104+
return this.state == State.IDLE && !this.bqConnection.isClosed();
105+
}
106+
99107
boolean isClosed() {
100-
return this.state == State.CLOSED || this.bqConnection.isClosed();
108+
return this.state == State.CLOSED
109+
|| this.state == State.RETIRED
110+
|| this.bqConnection.isClosed();
101111
}
102112

103113
@VisibleForTesting
104114
boolean isListenerPooled(ConnectionEventListener listener) {
105115
synchronized (stateLock) {
106-
return listeners.contains(listener);
116+
return this.internalPoolListener == listener || this.listeners.contains(listener);
117+
}
118+
}
119+
120+
void registerInternalPoolListener(PooledConnectionListener poolManager) {
121+
if (poolManager == null) {
122+
return;
123+
}
124+
synchronized (stateLock) {
125+
if (isHolderTerminalLocked()
126+
|| this.bqConnection.isClosed()
127+
|| this.detachedFromInternalPool) {
128+
return;
129+
}
130+
this.internalPoolListener = poolManager;
131+
}
132+
}
133+
134+
BigQueryConnection claimPhysicalForReuse(PooledConnectionListener poolManager) {
135+
synchronized (stateLock) {
136+
if (this.state != State.IDLE
137+
|| this.bqConnection.isClosed()
138+
|| this.activeHandle != null
139+
|| this.resettingHandle != null
140+
|| this.detachedFromInternalPool
141+
|| this.nonPoolListenerAttached
142+
|| poolManager == null
143+
|| this.internalPoolListener != poolManager
144+
|| !this.listeners.isEmpty()) {
145+
return null;
146+
}
147+
this.state = State.RETIRED;
148+
this.internalPoolListener = null;
149+
this.listeners.clear();
150+
return this.bqConnection;
151+
}
152+
}
153+
154+
void closeIfIdleAndSoleListener(ConnectionEventListener expectedListener) {
155+
synchronized (physicalLock) {
156+
synchronized (stateLock) {
157+
if (this.state != State.IDLE
158+
|| this.bqConnection.isClosed()
159+
|| this.activeHandle != null
160+
|| this.resettingHandle != null
161+
|| !isSolelyOwnedByPoolListenerLocked(expectedListener)) {
162+
return;
163+
}
164+
this.state = State.CLOSED;
165+
this.internalPoolListener = null;
166+
this.listeners.clear();
167+
}
168+
try {
169+
this.bqConnection.close();
170+
} catch (SQLException ex) {
171+
LOG.warning(ex, "Failed to close excess pooled connection");
172+
}
107173
}
108174
}
109175

@@ -114,11 +180,37 @@ PooledConnectionInvocationHandler getActiveHandleForTesting() {
114180
}
115181
}
116182

183+
private boolean isSolelyOwnedByPoolListenerLocked(ConnectionEventListener expectedListener) {
184+
if (this.nonPoolListenerAttached || expectedListener == null) {
185+
return false;
186+
}
187+
if (!this.detachedFromInternalPool && this.internalPoolListener != null) {
188+
return this.internalPoolListener == expectedListener && this.listeners.isEmpty();
189+
}
190+
return this.internalPoolListener == null
191+
&& this.listeners.size() == 1
192+
&& this.listeners.get(0) == expectedListener;
193+
}
194+
195+
private List<ConnectionEventListener> snapshotAllListenersLocked() {
196+
List<ConnectionEventListener> snapshot =
197+
new ArrayList<>(this.listeners.size() + (this.internalPoolListener != null ? 1 : 0));
198+
if (this.internalPoolListener != null) {
199+
snapshot.add(this.internalPoolListener);
200+
}
201+
snapshot.addAll(this.listeners);
202+
return snapshot;
203+
}
204+
117205
private boolean isHolderTerminalLocked() {
118-
return this.state == State.CLOSED;
206+
return this.state == State.CLOSED || this.state == State.RETIRED;
119207
}
120208

121209
private void checkHolderOpenLocked() throws BigQueryJdbcException {
210+
if (this.state == State.RETIRED) {
211+
throw new BigQueryJdbcException(
212+
"PooledConnection was retired and recycled by PooledConnectionDataSource.");
213+
}
122214
if (this.state == State.CLOSED || this.bqConnection.isClosed()) {
123215
throw new BigQueryJdbcException("PooledConnection is closed.");
124216
}
@@ -134,6 +226,10 @@ public Connection getConnection() throws SQLException {
134226
PooledConnectionInvocationHandler previousHandle = null;
135227
boolean needsReset = false;
136228
synchronized (stateLock) {
229+
if (this.state == State.RETIRED) {
230+
throw new BigQueryJdbcException(
231+
"PooledConnection was retired and recycled by PooledConnectionDataSource.");
232+
}
137233
if (isHolderTerminalLocked()) {
138234
throw new BigQueryJdbcException("PooledConnection is closed.");
139235
}
@@ -228,6 +324,7 @@ public void addConnectionEventListener(ConnectionEventListener listener) {
228324
if (listener == null) {
229325
return;
230326
}
327+
PooledConnectionListener detachedInternal = null;
231328
synchronized (stateLock) {
232329
if (isHolderTerminalLocked()
233330
|| this.bqConnection.isClosed()
@@ -242,11 +339,23 @@ public void addConnectionEventListener(ConnectionEventListener listener) {
242339
"Listener pool capacity exceeded: " + listenerPoolSize);
243340
}
244341
this.listeners.add(listener);
342+
if (!(listener instanceof PooledConnectionListener) || this.listeners.size() > 1) {
343+
this.nonPoolListenerAttached = true;
344+
}
345+
if (this.nonPoolListenerAttached
346+
|| (this.internalPoolListener != null && listener != this.internalPoolListener)) {
347+
this.detachedFromInternalPool = true;
348+
detachedInternal = this.internalPoolListener;
349+
this.internalPoolListener = null;
350+
}
245351
} finally {
246352
LOG.finer("++exit++");
247353
}
248354
}
249355
}
356+
if (detachedInternal != null) {
357+
detachedInternal.removeConnection(this);
358+
}
250359
}
251360

252361
@Override
@@ -294,7 +403,7 @@ void connectionHandleClosed(PooledConnectionInvocationHandler handle) throws SQL
294403
new BigQueryJdbcException("Underlying physical connection was closed.");
295404
} else {
296405
this.state = State.IDLE;
297-
listenersToNotify = new ArrayList<>(this.listeners);
406+
listenersToNotify = snapshotAllListenersLocked();
298407
}
299408
}
300409
}
@@ -331,7 +440,8 @@ void abortHandle(PooledConnectionInvocationHandler handle, Executor executor)
331440
this.state = State.CLOSED;
332441
this.activeHandle = null;
333442
this.resettingHandle = null;
334-
snapshot = new ArrayList<>(this.listeners);
443+
snapshot = snapshotAllListenersLocked();
444+
this.internalPoolListener = null;
335445
this.listeners.clear();
336446
}
337447

@@ -455,7 +565,8 @@ private TerminalTransition transitionToClosedAndMarkActiveHandle() {
455565
this.activeHandle = null;
456566
}
457567
this.resettingHandle = null;
458-
List<ConnectionEventListener> snapshot = new ArrayList<>(this.listeners);
568+
List<ConnectionEventListener> snapshot = snapshotAllListenersLocked();
569+
this.internalPoolListener = null;
459570
this.listeners.clear();
460571
return new TerminalTransition(snapshot, previous);
461572
}

‎java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSource.java‎

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -16,54 +16,54 @@
1616

1717
package com.google.cloud.bigquery.jdbc;
1818

19-
import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException;
2019
import com.google.cloud.bigquery.jdbc.telemetry.v1.DriverFeature;
2120
import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager;
2221
import com.google.common.annotations.VisibleForTesting;
23-
import java.sql.Connection;
2422
import java.sql.SQLException;
2523
import javax.sql.ConnectionPoolDataSource;
2624
import javax.sql.PooledConnection;
2725

2826
public class PooledConnectionDataSource extends DataSource implements ConnectionPoolDataSource {
2927
private static final BigQueryJdbcCustomLogger LOG =
3028
new BigQueryJdbcCustomLogger(PooledConnectionDataSource.class.getName());
31-
private PooledConnectionListener connectionPoolManager = null;
32-
Connection bqConnection = null;
29+
private volatile PooledConnectionListener connectionPoolManager = null;
3330

3431
@Override
3532
public PooledConnection getPooledConnection() throws SQLException {
36-
if (connectionPoolManager != null && !connectionPoolManager.isConnectionPoolEmpty()) {
37-
return connectionPoolManager.getPooledConnection();
38-
}
39-
// Create the Underlying physical connection
40-
if (bqConnection == null) {
41-
bqConnection = super.getConnection();
42-
}
43-
if (bqConnection == null) {
44-
throw new BigQueryJdbcRuntimeException(
45-
"Cannot get pooled connection: unable to get underlying physical connection");
46-
}
47-
BigQueryConnection physicalConnection;
48-
if (bqConnection.isWrapperFor(BigQueryConnection.class)) {
49-
physicalConnection = bqConnection.unwrap(BigQueryConnection.class);
50-
} else {
51-
physicalConnection = (BigQueryConnection) bqConnection;
52-
}
53-
Long connectionPoolSize = physicalConnection.getConnectionPoolSize();
54-
if (connectionPoolManager == null) {
55-
connectionPoolManager = new PooledConnectionListener(connectionPoolSize);
33+
PooledConnectionListener poolManager = this.connectionPoolManager;
34+
if (poolManager != null) {
35+
BigQueryPooledConnection candidate;
36+
while ((candidate = poolManager.getPooledConnection()) != null) {
37+
BigQueryConnection reusedPhysical = candidate.claimPhysicalForReuse(poolManager);
38+
if (reusedPhysical != null) {
39+
BigQueryPooledConnection recycled = new BigQueryPooledConnection(reusedPhysical);
40+
recycled.registerInternalPoolListener(poolManager);
41+
TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_CONNECTION_POOLING);
42+
return recycled;
43+
}
44+
}
5645
}
46+
47+
BigQueryConnection physicalConnection = super.getConnection().unwrap(BigQueryConnection.class);
48+
poolManager = getOrInitConnectionPoolManager(physicalConnection.getConnectionPoolSize());
5749
BigQueryPooledConnection bqPooledConnection = new BigQueryPooledConnection(physicalConnection);
58-
bqPooledConnection.addConnectionEventListener(connectionPoolManager);
50+
bqPooledConnection.registerInternalPoolListener(poolManager);
5951

6052
TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_CONNECTION_POOLING);
6153
return bqPooledConnection;
6254
}
6355

64-
@VisibleForTesting
65-
void setConnection(Connection connection) {
66-
this.bqConnection = connection;
56+
private PooledConnectionListener getOrInitConnectionPoolManager(Long resolvedPoolSize) {
57+
PooledConnectionListener existing = this.connectionPoolManager;
58+
if (existing != null) {
59+
return existing;
60+
}
61+
synchronized (this) {
62+
if (this.connectionPoolManager == null) {
63+
this.connectionPoolManager = new PooledConnectionListener(resolvedPoolSize);
64+
}
65+
return this.connectionPoolManager;
66+
}
6767
}
6868

6969
@VisibleForTesting

0 commit comments

Comments
 (0)