Skip to content

Instantly share code, notes, and snippets.

@ddimtirov
Created September 3, 2012 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddimtirov/3608443 to your computer and use it in GitHub Desktop.
Save ddimtirov/3608443 to your computer and use it in GitHub Desktop.
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