Skip to content

Commit ef89a67

Browse files
committed
fix: fix channel not shut down properly exception.
Client being created has to be properly closed, otherwise during garbage collection an error will be reported showing channel not shutdown properly
1 parent 2dd8efc commit ef89a67

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

samples/snippets/src/main/java/com/example/bigquerystorage/WriteToDefaultStream.java

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@
4949
import org.threeten.bp.Duration;
5050

5151
public class WriteToDefaultStream {
52-
52+
5353
public static void runWriteToDefaultStream()
5454
throws DescriptorValidationException, InterruptedException, IOException {
5555
// TODO(developer): Replace these variables before running the sample.
@@ -138,6 +138,8 @@ private static class DataWriter {
138138

139139
private static final int MAX_RECREATE_COUNT = 3;
140140

141+
private BigQueryWriteClient client;
142+
141143
// Track the number of in-flight requests to wait for all responses before shutting down.
142144
private final Phaser inflightRequestCount = new Phaser(1);
143145
private final Object lock = new Object();
@@ -163,12 +165,16 @@ public void initialize(TableName parentTable)
163165
.setMaxRetryDelay(Duration.ofMinutes(1))
164166
.build();
165167

168+
// Initialize client without settings, internally within stream writer a new client will be
169+
// created with full settings.
170+
client = BigQueryWriteClient.create();
171+
166172
// Use the JSON stream writer to send records in JSON format. Specify the table name to write
167173
// to the default stream.
168174
// For more information about JsonStreamWriter, see:
169175
// https://googleapis.dev/java/google-cloud-bigquerystorage/latest/com/google/cloud/bigquery/storage/v1/JsonStreamWriter.html
170176
streamWriter =
171-
JsonStreamWriter.newBuilder(parentTable.toString(), BigQueryWriteClient.create())
177+
JsonStreamWriter.newBuilder(parentTable.toString(), client)
172178
.setExecutorProvider(
173179
FixedExecutorProvider.create(Executors.newScheduledThreadPool(100)))
174180
.setChannelProvider(
@@ -195,7 +201,7 @@ public void append(AppendContext appendContext)
195201
&& recreateCount.getAndIncrement() < MAX_RECREATE_COUNT) {
196202
streamWriter =
197203
JsonStreamWriter.newBuilder(
198-
streamWriter.getStreamName(), BigQueryWriteClient.create())
204+
streamWriter.getStreamName(), client)
199205
.build();
200206
this.error = null;
201207
}
@@ -217,6 +223,7 @@ public void cleanup() {
217223
// Wait for all in-flight requests to complete.
218224
inflightRequestCount.arriveAndAwaitAdvance();
219225

226+
client.close();
220227
// Close the connection to the server.
221228
streamWriter.close();
222229

0 commit comments

Comments
 (0)