Skip to content

Commit

Permalink
Fix flaky SlidingWindowTest (#1242)
Browse files Browse the repository at this point in the history
Fixes issue #956.

Signed-off-by: Stephan Schroevers <[email protected]>
  • Loading branch information
Stephan202 authored Dec 27, 2024
1 parent 3fdf1e5 commit 4365604
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class SlidingWindow<T> {
private int currentBucket;
private long lastRotateTimestampMillis;
private final long durationBetweenRotatesMillis;
LongSupplier currentTimeMillis = System::currentTimeMillis; // to be replaced in unit tests
private final LongSupplier currentTimeMillis;

/**
* Example: If the {@code maxAgeSeconds} is 60 and {@code ageBuckets} is 3, then 3 instances of
Expand All @@ -39,13 +39,24 @@ public class SlidingWindow<T> {
* @param maxAgeSeconds after this amount of time an instance of T gets evicted.
* @param ageBuckets number of age buckets.
*/
@SuppressWarnings("unchecked")
public SlidingWindow(
Class<T> clazz,
Supplier<T> constructor,
ObjDoubleConsumer<T> observeFunction,
long maxAgeSeconds,
int ageBuckets) {
this(clazz, constructor, observeFunction, maxAgeSeconds, ageBuckets, System::currentTimeMillis);
}

// VisibleForTesting
@SuppressWarnings("unchecked")
SlidingWindow(
Class<T> clazz,
Supplier<T> constructor,
ObjDoubleConsumer<T> observeFunction,
long maxAgeSeconds,
int ageBuckets,
LongSupplier currentTimeMillis) {
this.constructor = constructor;
this.observeFunction = observeFunction;
this.ringBuffer = (T[]) Array.newInstance(clazz, ageBuckets);
Expand All @@ -55,6 +66,7 @@ public SlidingWindow(
this.currentBucket = 0;
this.lastRotateTimestampMillis = currentTimeMillis.getAsLong();
this.durationBetweenRotatesMillis = TimeUnit.SECONDS.toMillis(maxAgeSeconds) / ageBuckets;
this.currentTimeMillis = currentTimeMillis;
}

/** Get the currently active instance of {@code T}. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,12 @@ public void setUp() {
currentTimeMillis.set(startTime);
ringBuffer =
new SlidingWindow<>(
Observer.class, Observer::new, Observer::observe, maxAgeSeconds, ageBuckets);
ringBuffer.currentTimeMillis = currentTimeMillis::get;
Observer.class,
Observer::new,
Observer::observe,
maxAgeSeconds,
ageBuckets,
currentTimeMillis::get);
}

@Test
Expand Down

0 comments on commit 4365604

Please sign in to comment.