Create a gist now

Instantly share code, notes, and snippets.

Groovy implementation (untested) for Cedric's SlidingWindowMap
import java.util.concurrent.PriorityBlockingQueue
import java.util.concurrent.ArrayBlockingQueue
public class SlidingWindowMap
def queue
def periodMs
public SlidingWindowMap(Set<String> keys, int maxCount, long periodMs)
queue = new PriorityBlockingQueue(keys.size(), { a, b -> (a[1].size() <=> b[1].size()) ?: (a[1].peek() <=> b[1].peek()) } as Comparator)
queue.addAll(keys.collect { [it, new ArrayBlockingQueue<Long>(maxCount)] })
this.periodMs = periodMs
* @return a key that has been used less than `maxCount` times during the
* past `periodMs` milliseconds or null if no such key exists.
public String getNextKey()
// Get the least used key with oldest usage.
def keyrec = queue.poll()
if (keyrec) {
ArrayBlockingQueue<Long> uses = keyrec[1]
// Expire uses earlier than the time window.
while (uses.size() && uses.peek() < System.currentTimeMillis() - periodMs) {
// Try to add the timestamp for this usage.
def useable = uses.offer(System.currentTimeMillis())
// Put the keyrec back into the queue.
if (useable) return keyrec[0]
return null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment