Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix flaky SlidingWindowTest #1242

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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