Skip to content

Instantly share code, notes, and snippets.

@Tea-Ayataka
Last active September 15, 2018 05:16
Show Gist options
  • Save Tea-Ayataka/139aea45e0ffd84549ddd339691aec49 to your computer and use it in GitHub Desktop.
Save Tea-Ayataka/139aea45e0ffd84549ddd339691aec49 to your computer and use it in GitHub Desktop.
Kotlin Simple Rate Limiter
class RateLimiter(private val period: Long, private val rate: Int) {
private val times = LinkedList<Long>()
fun check(): Boolean {
synchronized(times) {
val currentTime = System.currentTimeMillis()
times.removeIf { it < currentTime - period }
val isLimited = times.size >= rate
if (!isLimited) {
times.add(currentTime)
}
return isLimited
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment