public class RateLimit extends Object
This method check()
can be called frequently. It will however only return true after a certain
amount of time has elapsed or after a number of calls where made. The mode depends on how the object was created.
As an example, this can be used in an inner loop if one wants to print out the current status every once in a while. Since writing to System.out is comparatively slow, it's a good idea to apply a rate limit:
RateLimit limit = RateLimit.everyNthCall(1000);
for(int i = 0; i < 100000; i++) {
// ...smart computation here...
if (limit.check()) {
System.out.println(i);
}
}
Modifier and Type | Method and Description |
---|---|
boolean |
check()
Checks whether the rate limit constraints permit another call or not.
|
static RateLimit |
everyNthCall(long n)
Creates a new call based rate limit.
|
static RateLimit |
nTimesPerInterval(long interval,
TimeUnit unit,
int permitsPerInterval)
Creates a new time based rate limit which permits up to N calls per interval.
|
static RateLimit |
timeInterval(long interval,
TimeUnit unit)
Creates a new time based rate limit.
|
String |
toString() |
public static RateLimit everyNthCall(long n)
Calling check()
on will only return true every n-th call and false otherwise.
n
- the number of calls to skip (returning false) by check()
before true
is returnedpublic static RateLimit timeInterval(long interval, TimeUnit unit)
Calling check()
on will only return true every after the given amount of time has be passed
since the last time it returned true. Returns false otherwise.
interval
- the amount of time after a call to check()
returns true againunit
- the unit for amountpublic static RateLimit nTimesPerInterval(long interval, TimeUnit unit, int permitsPerInterval)
Calling check()
on will only return true N times in every given interval,
false otherwise.
interval
- the amount of time after a call to check()
returns true againunit
- the unit for amountpermitsPerInterval
- the number of times to return true per intervalpublic boolean check()
Copyright © 2018. All rights reserved.