Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Coding challenge: a sliding window map
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
You can’t perform that action at this time.