Skip to content

Instantly share code, notes, and snippets.

@john-kurkowski
Forked from Rogach/SlidingWindowMap.scala
Created September 3, 2012 08:58
Show Gist options
  • Save john-kurkowski/3607988 to your computer and use it in GitHub Desktop.
Save john-kurkowski/3607988 to your computer and use it in GitHub Desktop.
SlidingWindowMap
class SlidingWindowMap(keys: Set[String], maxCount: Int, periodMs: Int) {
val times = new collection.mutable.HashMap[String, Vector[Long]]() with collection.mutable.SynchronizedMap[String, Vector[Long]]
times ++= keys.map(k => (k, Vector[Long]()))
def nextKey: Option[String] = {
val now = System.currentTimeMillis
times.synchronized {
val trimmedTimes = times.toStream map { case (k, usage) =>
val trimmedUsage = usage dropWhile (_ < now - periodMs)
times(k) = trimmedUsage
(k, trimmedUsage)
}
trimmedTimes find (_._2.length < maxCount) map (_._1)
}
}
def addUsage(key: String) {
times(key) = times.getOrElse(key, Vector[Long]()) :+ System.currentTimeMillis
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment