Created
September 3, 2012 05:52
-
-
Save jimwhite/3607071 to your computer and use it in GitHub Desktop.
Groovy implementation (untested) for Cedric's SlidingWindowMap
This file contains 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.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