Skip to content

Instantly share code, notes, and snippets.

@jimwhite
Created September 3, 2012 05:52
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 jimwhite/3607071 to your computer and use it in GitHub Desktop.
Save jimwhite/3607071 to your computer and use it in GitHub Desktop.
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) {
uses.take()
}
// Try to add the timestamp for this usage.
def useable = uses.offer(System.currentTimeMillis())
// Put the keyrec back into the queue.
queue.add(keyrec)
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