-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTokenBucket.java
More file actions
28 lines (25 loc) · 880 Bytes
/
Copy pathTokenBucket.java
File metadata and controls
28 lines (25 loc) · 880 Bytes
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
import java.util.function.DoubleSupplier;
/** Token-bucket rate limiter. Not thread-safe; guard externally if shared. */
public final class TokenBucket {
private final double rate, capacity;
private double tokens, last;
private final DoubleSupplier now;
public TokenBucket(double ratePerSec, double capacity, DoubleSupplier now) {
this.rate = ratePerSec;
this.capacity = capacity;
this.tokens = capacity;
this.now = now;
this.last = now.getAsDouble();
}
/** Refill by elapsed time, then take {@code cost} tokens if available. */
public boolean allow(double cost) {
double t = now.getAsDouble();
tokens = Math.min(capacity, tokens + (t - last) * rate);
last = t;
if (tokens >= cost) {
tokens -= cost;
return true;
}
return false;
}
}