Skip to content

Instantly share code, notes, and snippets.

@Rogach
Created September 3, 2012 03:51
Show Gist options
  • Save Rogach/3606621 to your computer and use it in GitHub Desktop.
Save Rogach/3606621 to your computer and use it in GitHub Desktop.
SlidingWindowMap
class SlidingWindowMap(keys: Set[String], maxCount: Int, periodMs: Int) {
val times = collection.mutable.Map(keys.map(k => (k, Vector[Long]())).toList:_*)
def nextKey: Option[String] = {
val now = System.currentTimeMillis
this.synchronized {
val key = times.find(_._2.dropWhile(_ < now - periodMs).size < maxCount).map(_._1)
key.foreach { k => times(k) = times(k).dropWhile(_ < now - periodMs) :+ now }
key
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment