From 9a43fb206bc556642a160de3d10301383e11c88d Mon Sep 17 00:00:00 2001 From: Sergey Balabanov <65374294+sbalabanov@users.noreply.github.com> Date: Mon, 21 Apr 2025 18:28:28 -0700 Subject: [PATCH] Make Stopwatch closeable So it could be used with try-with-resources --- .../java/com/uber/m3/tally/Stopwatch.java | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/com/uber/m3/tally/Stopwatch.java b/core/src/main/java/com/uber/m3/tally/Stopwatch.java index 369bfbf..b9dbb76 100644 --- a/core/src/main/java/com/uber/m3/tally/Stopwatch.java +++ b/core/src/main/java/com/uber/m3/tally/Stopwatch.java @@ -25,8 +25,16 @@ * relies on values being recorded as nanosecond-level timestamps. There is no * assumption that {@code startNanos} is related to the current time, but successive recordings * of the stopwatch are comparable with one another. + *
+ * This class implements {@link AutoCloseable}, so it can be used with try-with-resources to + * automatically call {@link #stop()} when the try block exits. + *
+ * try (Stopwatch stopwatch = timer.start()) {
+ * // Do something
+ * } // stopwatch.stop() is automatically called here
+ *
*/
-public class Stopwatch {
+public class Stopwatch implements AutoCloseable {
private final long startNanos;
private final StopwatchRecorder recorder;
@@ -56,4 +64,13 @@ public void stop() {
public void Stop() {
stop();
}
+
+ /**
+ * Closes this stopwatch by calling {@link #stop()}.
+ * This method is automatically called when used in a try-with-resources block.
+ */
+ @Override
+ public void close() {
+ stop();
+ }
}