Skip to content

Instantly share code, notes, and snippets.

@grazer
Last active December 22, 2015 17:19
Show Gist options
  • Save grazer/6505639 to your computer and use it in GitHub Desktop.
Save grazer/6505639 to your computer and use it in GitHub Desktop.
class TokenBucket(msgPerSecond:Long, bucketSize:Long) {
var prev = 0L
var tokens = bucketSize
def limit(func: => Any): Any = {
val current = System.currentTimeMillis
val delta = current-prev
prev = current
tokens += delta/1000.0 * msgPerSecond
if (tokens > bucketSize)
tokens = bucketSize
if (tokens > 0)
func
tokens -= 1
}
}
scala> var tb = new TokenBucket(10, 6)
tb: TokenBucket = TokenBucket@5c2f4f8b
scala> (1 to 10) foreach( i => tb.limit { println(i) })
1
2
3
4
5
6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment