-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRateLimiter.java
35 lines (29 loc) · 1.06 KB
/
RateLimiter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.concurrent.Callable;
/**
* A token bucket based rate-limiter.
*
* This class should implement a "soft" rate limiter by adding maxBytesPerSecond tokens to the bucket every second,
* or a "hard" rate limiter by resetting the bucket to maxBytesPerSecond tokens every second.
*/
public class RateLimiter implements Callable<Void> {
private final TokenBucket tokenBucket;
private final Long maxBytesPerSecond;
private final long PER_SECOND = 1000;
RateLimiter(Long maxBytesPerSecond) {
this.tokenBucket = TokenBucket.getInstance();
this.maxBytesPerSecond = (maxBytesPerSecond == null) ? Long.MAX_VALUE : maxBytesPerSecond;
}
public Void call() {
// rate limiter resets the TokenBucket to maxBytesPerSecond every second
try {
while(!Thread.interrupted()) {
this.tokenBucket.set(this.maxBytesPerSecond);
Thread.sleep(PER_SECOND);
}
} catch (InterruptedException e) {
// do nothing with the exception
// exits the program cleanly
}
return null;
}
}