public class RateLimiter extends Object
increment()
(or if batching
for when what this is counting
happens and then call isRateLimited()
to check if the rate limit has been reached.
You should check if the rate is limited at least once per your given time interval. If you check too late, your
counted measure will be averaged over the time duration since the last check, which may or may not
cause your rate limit criteria to be violated. This can happen if your increments or adds are bursty so you exceed
the rate limit within your time interval but you neglect to check it for a long enough time interval where the burst
is spread out over bringing the overall rate lower than your configured maximum and yielding a false negative.Modifier and Type | Field and Description |
---|---|
static int |
SECOND |
Constructor and Description |
---|
RateLimiter(int maximum)
Create an instance of this that uses a default time window of
SECOND ms. |
RateLimiter(int maximum,
int timeInterval)
Create an instance of this that uses the given maximum and the given time interval.
|
Modifier and Type | Method and Description |
---|---|
void |
add(int n)
Increment the measure that this is counting by the given positive number.
|
double |
getCurrentRate()
Returns the absolute current rate since the last check interval.
|
void |
increment()
Increment the measure that this is counting by one.
|
boolean |
isRateLimited()
Checks to see if this is rate limited.
|
public static final int SECOND
public RateLimiter(int maximum) throws IllegalArgumentException
SECOND
ms.maximum
- A positive maximum count that this uses as the upper limit per the time interval.IllegalArgumentException
- if the maximum was not positive.public RateLimiter(int maximum, int timeInterval) throws IllegalArgumentException
maximum
- A positive maximum count that is the limit for each time interval.timeInterval
- The rate check will be done only at most once for this positive time interval in milliseconds.IllegalArgumentException
- if the maximum or the time interval were not positive.public void increment()
public void add(int n)
n
- The number to add to the count.IllegalArgumentException
- if the given number was not positive.public boolean isRateLimited()
public double getCurrentRate()
Copyright © 2021. All rights reserved.