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 9470de77050..bdbba6d619d 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 @@ -53,11 +53,16 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; import java.util.stream.Collectors; /** The main class for gRPC Google Cloud Platform Observability features. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/8869") public final class GcpObservability implements AutoCloseable { + + private static final Logger logger = Logger.getLogger(GcpObservability.class.getName()); private static final int METRICS_EXPORT_INTERVAL = 30; @VisibleForTesting static final ImmutableSet SERVICES_TO_EXCLUDE = ImmutableSet.of( @@ -117,6 +122,16 @@ public void close() { throw new IllegalStateException("GcpObservability already closed!"); } 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)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + logger.log(Level.SEVERE, "Caught exception during sleep", e); + } + } instance = null; } }