Last active
April 20, 2017 13:56
-
-
Save johnou/027177cf90682fa93969cc8d272af813 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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