Skip to content

Commit c3b9b7e

Browse files
committed
ensure garbage collection
1 parent 4532736 commit c3b9b7e

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed

java-bigquery/google-cloud-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -840,6 +840,8 @@ public void close() throws SQLException {
840840
throw new BigQueryJdbcException(ex);
841841
} catch (InterruptedException e) {
842842
throw new BigQueryJdbcRuntimeException(e);
843+
} finally {
844+
BigQueryJdbcMdc.removeInstance(this);
843845
}
844846
this.isClosed = true;
845847
}

java-bigquery/google-cloud-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcMdc.java

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ public class BigQueryJdbcMdc {
3232
new ConcurrentHashMap<>();
3333

3434
/** Allocates an exclusive InheritableThreadLocal and registers the connection mapping. */
35+
private static final InheritableThreadLocal<String> currentConnectionId = new InheritableThreadLocal<>();
36+
3537
public static void registerInstance(BigQueryConnection connection, String id) {
3638
if (connection != null) {
3739
String cleanId =
@@ -44,6 +46,7 @@ public static void registerInstance(BigQueryConnection connection, String id) {
4446
return "JdbcConnection-" + numericPart;
4547
});
4648

49+
currentConnectionId.set(cleanId);
4750
InheritableThreadLocal<String> threadLocal =
4851
instanceLocals.computeIfAbsent(connection, k -> new InheritableThreadLocal<>());
4952
threadLocal.set(cleanId);
@@ -69,19 +72,26 @@ public static String getConnectionId(BigQueryConnection connection) {
6972
* Returns the connection ID carried by any registered active connection on the current thread.
7073
*/
7174
public static String getConnectionId() {
72-
for (InheritableThreadLocal<String> local : instanceLocals.values()) {
73-
String val = local.get();
74-
if (val != null) {
75-
return val;
75+
return currentConnectionId.get();
76+
}
77+
78+
/** Clears the connection ID context from all active connection contexts on the current thread. */
79+
public static void removeInstance(BigQueryConnection connection) {
80+
if (connection != null) {
81+
InheritableThreadLocal<String> local = instanceLocals.remove(connection);
82+
if (local != null) {
83+
local.remove();
7684
}
85+
instanceIds.remove(connection);
7786
}
78-
return null;
7987
}
8088

81-
/** Clears the connection ID context from all active connection contexts on the current thread. */
8289
public static void clear() {
90+
currentConnectionId.remove();
8391
for (InheritableThreadLocal<String> local : instanceLocals.values()) {
8492
local.remove();
8593
}
94+
instanceLocals.clear();
95+
instanceIds.clear();
8696
}
8797
}

0 commit comments

Comments
 (0)