Skip to content

Commit 4365604

Browse files
authored
Fix flaky SlidingWindowTest (#1242)
Fixes issue #956. Signed-off-by: Stephan Schroevers <[email protected]>
1 parent 3fdf1e5 commit 4365604

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/SlidingWindow.java

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public class SlidingWindow<T> {
2626
private int currentBucket;
2727
private long lastRotateTimestampMillis;
2828
private final long durationBetweenRotatesMillis;
29-
LongSupplier currentTimeMillis = System::currentTimeMillis; // to be replaced in unit tests
29+
private final LongSupplier currentTimeMillis;
3030

3131
/**
3232
* Example: If the {@code maxAgeSeconds} is 60 and {@code ageBuckets} is 3, then 3 instances of
@@ -39,13 +39,24 @@ public class SlidingWindow<T> {
3939
* @param maxAgeSeconds after this amount of time an instance of T gets evicted.
4040
* @param ageBuckets number of age buckets.
4141
*/
42-
@SuppressWarnings("unchecked")
4342
public SlidingWindow(
4443
Class<T> clazz,
4544
Supplier<T> constructor,
4645
ObjDoubleConsumer<T> observeFunction,
4746
long maxAgeSeconds,
4847
int ageBuckets) {
48+
this(clazz, constructor, observeFunction, maxAgeSeconds, ageBuckets, System::currentTimeMillis);
49+
}
50+
51+
// VisibleForTesting
52+
@SuppressWarnings("unchecked")
53+
SlidingWindow(
54+
Class<T> clazz,
55+
Supplier<T> constructor,
56+
ObjDoubleConsumer<T> observeFunction,
57+
long maxAgeSeconds,
58+
int ageBuckets,
59+
LongSupplier currentTimeMillis) {
4960
this.constructor = constructor;
5061
this.observeFunction = observeFunction;
5162
this.ringBuffer = (T[]) Array.newInstance(clazz, ageBuckets);
@@ -55,6 +66,7 @@ public SlidingWindow(
5566
this.currentBucket = 0;
5667
this.lastRotateTimestampMillis = currentTimeMillis.getAsLong();
5768
this.durationBetweenRotatesMillis = TimeUnit.SECONDS.toMillis(maxAgeSeconds) / ageBuckets;
69+
this.currentTimeMillis = currentTimeMillis;
5870
}
5971

6072
/** Get the currently active instance of {@code T}. */

prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/SlidingWindowTest.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,12 @@ public void setUp() {
4848
currentTimeMillis.set(startTime);
4949
ringBuffer =
5050
new SlidingWindow<>(
51-
Observer.class, Observer::new, Observer::observe, maxAgeSeconds, ageBuckets);
52-
ringBuffer.currentTimeMillis = currentTimeMillis::get;
51+
Observer.class,
52+
Observer::new,
53+
Observer::observe,
54+
maxAgeSeconds,
55+
ageBuckets,
56+
currentTimeMillis::get);
5357
}
5458

5559
@Test

0 commit comments

Comments
 (0)