Created
September 3, 2012 03:51
-
-
Save Rogach/3606621 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 = 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