Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class SlidingTimeThreshold {
private final long[] samples;
private final long windowMillis;
private int index;
public SlidingTimeThreshold(final long window, final TimeUnit timeUnit, final int threshold) {
this.windowMillis = timeUnit.toMillis(window);
this.samples = new long[threshold];
}
public synchronized boolean update() {
long currentTs = TimeSource.currentTimeMillis();
samples[index] = currentTs;
index = (index + 1) % samples.length;
if (samples[index] <= currentTs - windowMillis) {
return false;
} else {
return true;
}
}
}
public class SlidingTimeThresholdTest {
private SlidingTimeThreshold slidingTimeThreshold;
@Before
public void setUp() throws Exception {
slidingTimeThreshold = new SlidingTimeThreshold(1500, TimeUnit.MILLISECONDS, 20);
}
@Test
public void testSlidingIterate() throws Exception {
for (int i = 0; i < 30; i++) {
assertFalse(slidingTimeThreshold.update());
TimeSource.advance(2000);
}
}
@Test
public void testThreshold() throws Exception {
for (int i = 0; i < 19; i++) {
assertFalse(slidingTimeThreshold.update());
}
assertTrue(slidingTimeThreshold.update());
TimeSource.advance(2000);
assertFalse(slidingTimeThreshold.update());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.