-
-
Save john-kurkowski/3607988 to your computer and use it in GitHub Desktop.
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
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