Last active
March 11, 2021 02:52
-
-
Save nejckorasa/84dfa262c860cc7d8302d21757d9cabd to your computer and use it in GitHub Desktop.
Rate Limiter in Java
This file contains hidden or 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
| import java.time.Duration; | |
| public class RateLimiter { | |
| private long capacity; | |
| private long lastRefillTimeStamp; | |
| private long refillCountPerSecond; | |
| private long availableTokens; | |
| public RateLimiter(long capacity, Duration window) { | |
| this.capacity = capacity; | |
| lastRefillTimeStamp = System.currentTimeMillis(); | |
| refillCountPerSecond = capacity / window.getSeconds(); | |
| availableTokens = 0; | |
| } | |
| public long getAvailableTokens() { | |
| return this.availableTokens; | |
| } | |
| public synchronized boolean tryConsume() { | |
| refill(); | |
| if (availableTokens > 0) { | |
| --availableTokens; | |
| return true; | |
| } else { | |
| return false; | |
| } | |
| } | |
| private void refill() { | |
| long now = System.currentTimeMillis(); | |
| if (now > lastRefillTimeStamp) { | |
| long elapsedTime = now - lastRefillTimeStamp; | |
| long tokensToBeAdded = (elapsedTime / 1000) * refillCountPerSecond; | |
| if (tokensToBeAdded > 0) { | |
| availableTokens = Math.min(capacity, availableTokens + tokensToBeAdded); | |
| lastRefillTimeStamp = now; | |
| } | |
| } | |
| } | |
| } |
This file contains hidden or 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
| import java.time.Duration; | |
| import java.util.concurrent.ConcurrentHashMap; | |
| import java.util.concurrent.ConcurrentMap; | |
| public class RateLimitFactory { | |
| private final ConcurrentMap<String, RateLimiter> rateLimiters = new ConcurrentHashMap<>(); | |
| private long capacity; | |
| private Duration window; | |
| public RateLimitFactory(long capacity, Duration window) { | |
| this.capacity = capacity; | |
| this.window = window; | |
| } | |
| public RateLimiter get(String key) { | |
| return rateLimiters.computeIfAbsent(key, k -> new RateLimiter(capacity, window)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment