Skip to content

Instantly share code, notes, and snippets.

@johnou
Last active April 20, 2017 13:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnou/027177cf90682fa93969cc8d272af813 to your computer and use it in GitHub Desktop.
Save johnou/027177cf90682fa93969cc8d272af813 to your computer and use it in GitHub Desktop.
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