From 877a1fc5ac98f14c6c5029095b80a137b5cd44e9 Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Fri, 22 Dec 2023 15:43:28 +0100 Subject: [PATCH] Added check on rotate frequency without this change you can get an arithmetic exception if you pass a 0. Negative numbers don't make sense fixes gh-3068 --- .../core/instrument/distribution/TimeWindowMax.java | 9 ++++++++- .../core/instrument/distribution/TimeWindowMaxTest.java | 8 ++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowMax.java b/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowMax.java index b42f26c56d..fcd6e63d3d 100644 --- a/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowMax.java +++ b/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowMax.java @@ -54,7 +54,7 @@ public TimeWindowMax(Clock clock, DistributionStatisticConfig config) { public TimeWindowMax(Clock clock, long rotateFrequencyMillis, int bufferLength) { this.clock = clock; - this.durationBetweenRotatesMillis = rotateFrequencyMillis; + this.durationBetweenRotatesMillis = checkPositive(rotateFrequencyMillis); this.lastRotateTimestampMillis = clock.wallTime(); this.currentBucket = 0; @@ -64,6 +64,13 @@ public TimeWindowMax(Clock clock, long rotateFrequencyMillis, int bufferLength) } } + private static long checkPositive(long rotateFrequencyMillis) { + if (rotateFrequencyMillis <= 0) { + throw new IllegalArgumentException("Rotate frequency must be a positive number"); + } + return rotateFrequencyMillis; + } + /** * For use by timer implementations. * @param sample The value to record. diff --git a/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/TimeWindowMaxTest.java b/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/TimeWindowMaxTest.java index 2d430e50d2..7295ee64a4 100644 --- a/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/TimeWindowMaxTest.java +++ b/micrometer-core/src/test/java/io/micrometer/core/instrument/distribution/TimeWindowMaxTest.java @@ -16,6 +16,7 @@ package io.micrometer.core.instrument.distribution; import io.micrometer.core.instrument.MockClock; +import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.time.Duration; @@ -68,4 +69,11 @@ void testLongPeriodOfInactivity() { assertThat(timeWindowMax.poll()).isEqualTo(100500); // 666 | 500 | 100500 } + @Test + void throwsExceptionWhenRotateFrequency0() { + Assertions.assertThatThrownBy(() -> new TimeWindowMax(clock, 0, 3)) + .isInstanceOf(IllegalArgumentException.class) + .withFailMessage("Rotate frequency must be a positive number"); + } + }