Created
September 3, 2012 10:37
-
-
Save ddimtirov/3608443 to your computer and use it in GitHub Desktop.
Coding challenge: a sliding window map
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
import java.util.concurrent.DelayQueue | |
import java.util.concurrent.Delayed | |
import java.util.concurrent.TimeUnit | |
class SlidingWindowMap { | |
private periodMs | |
private available = new DelayQueue<DelayedKey<String>>() | |
SlidingWindowMap(Set<String> keys, int maxCount, long periodMs) { | |
this.periodMs = periodMs | |
keys.each { key -> maxCount.times { available << new DelayedKey<String>(payload: key) } } | |
} | |
/** | |
* @return a key that has been used less than `maxCount` times during the | |
* past `periodMs` milliseconds or null if no such key exists. | |
*/ | |
String getNextKey() { | |
def delayedKey = available.poll() | |
if (delayedKey) available << delayedKey.blockFor(periodMs) | |
return delayedKey?.payload | |
} | |
} | |
class DelayedKey<T> implements Delayed { | |
T payload | |
long targetTimestamp | |
long getDelay(TimeUnit unit) { unit.convert(targetTimestamp - System.currentTimeMillis(), TimeUnit.MILLISECONDS) } | |
int compareTo(Delayed o) { getDelay(TimeUnit.MILLISECONDS) <=> o.getDelay(TimeUnit.MILLISECONDS) } | |
DelayedKey<T> blockFor(long delayMs) { | |
targetTimestamp=System.currentTimeMillis() + delayMs | |
return this | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment