diff --git a/gcp-observability/src/main/java/io/grpc/gcp/observability/GcpObservability.java b/gcp-observability/src/main/java/io/grpc/gcp/observability/GcpObservability.java index 497a1eda30f..3ee14c19ef2 100644 --- a/gcp-observability/src/main/java/io/grpc/gcp/observability/GcpObservability.java +++ b/gcp-observability/src/main/java/io/grpc/gcp/observability/GcpObservability.java @@ -127,6 +127,15 @@ static GcpObservability grpcInit( /** Un-initialize/shutdown grpc-observability. */ @Override public void close() { + closeWithSleepTime(2 * METRICS_EXPORT_INTERVAL, TimeUnit.SECONDS); + } + + /** + * Method to close along with sleep time explicitly. + * + * @param sleepTime sleepTime + */ + void closeWithSleepTime(long sleepTime, TimeUnit timeUnit) { synchronized (GcpObservability.class) { if (instance == null) { throw new IllegalStateException("GcpObservability already closed!"); @@ -134,9 +143,7 @@ public void close() { sink.close(); if (config.isEnableCloudMonitoring() || config.isEnableCloudTracing()) { try { - // Sleeping before shutdown to ensure all metrics and traces are flushed - Thread.sleep( - TimeUnit.MILLISECONDS.convert(2 * METRICS_EXPORT_INTERVAL, TimeUnit.SECONDS)); + timeUnit.sleep(sleepTime); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.log(Level.SEVERE, "Caught exception during sleep", e); diff --git a/gcp-observability/src/test/java/io/grpc/gcp/observability/GcpObservabilityTest.java b/gcp-observability/src/test/java/io/grpc/gcp/observability/GcpObservabilityTest.java index 40f2fb01490..3c9ecb8d8fe 100644 --- a/gcp-observability/src/test/java/io/grpc/gcp/observability/GcpObservabilityTest.java +++ b/gcp-observability/src/test/java/io/grpc/gcp/observability/GcpObservabilityTest.java @@ -49,6 +49,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.util.concurrent.TimeUnit; @RunWith(JUnit4.class) public class GcpObservabilityTest { @@ -196,9 +197,9 @@ public void run() { mock(InternalLoggingServerInterceptor.Factory.class); when(serverInterceptorFactory.create()).thenReturn(serverInterceptor); - try (GcpObservability unused = - GcpObservability.grpcInit( - sink, config, channelInterceptorFactory, serverInterceptorFactory)) { + try { + GcpObservability gcpObservability = GcpObservability.grpcInit( + sink, config, channelInterceptorFactory, serverInterceptorFactory); List configurators = InternalConfiguratorRegistry.getConfigurators(); assertThat(configurators).hasSize(1); ObservabilityConfigurator configurator = (ObservabilityConfigurator) configurators.get(0); @@ -208,9 +209,11 @@ public void run() { assertThat(list.get(2)).isInstanceOf(ConditionalClientInterceptor.class); assertThat(configurator.serverInterceptors).hasSize(1); assertThat(configurator.tracerFactories).hasSize(2); + gcpObservability.closeWithSleepTime(3000, TimeUnit.MILLISECONDS); } catch (Exception e) { fail("Encountered exception: " + e); } + verify(sink).close(); } }