Package com.gmt2001.ratelimiters
Class WindowedRateLimiter
java.lang.Object
com.gmt2001.ratelimiters.WindowedRateLimiter
- Direct Known Subclasses:
WindowedSwitchingRateLimiter
Handles rate limiting using a window which resets a period of time after the first token is used
- Author:
- gmt2001
-
Field Summary
Fields -
Constructor Summary
ConstructorsConstructorDescriptionWindowedRateLimiter(long windowMS, int limit) ConstructorWindowedRateLimiter(Duration window, int limit) Constructor -
Method Summary
Modifier and TypeMethodDescriptionintbooleanintlimit()voidreset()Determines if the window has passed the next reset time, and resets the current token count if it hasbooleanAttempts to take a token, and starts a new window if the bucket was fullvoidwaitAndRun(Runnable command) Runs the specified command when a token is available, but does not take the token.voidwaitAndTakeToken(Runnable command) Takes a token and then runs the specified command.longwindowMS()
-
Field Details
-
windowMS
protected final long windowMS -
limit
protected final int limit -
mutex
-
nextReset
-
currentTokens
protected int currentTokens
-
-
Constructor Details
-
WindowedRateLimiter
Constructor- Parameters:
windowMS- The length of the windowlimit- The maximum number of tokens available during the window
-
WindowedRateLimiter
public WindowedRateLimiter(long windowMS, int limit) Constructor- Parameters:
windowMS- The length of the window, in millisecondslimit- The maximum number of tokens available during the window
-
-
Method Details
-
limit
public int limit()- Returns:
- The maximum number of tokens available during the window
-
windowMS
public long windowMS()- Returns:
- The length of the window, in milliseconds
-
isTokenAvailable
public boolean isTokenAvailable()- Returns:
trueif there is a token available
-
currentTokens
public int currentTokens()- Returns:
- The current number of tokens available
-
nextReset
- Returns:
- An
Instantindicating when the window will next reset
-
reset
public void reset()Determines if the window has passed the next reset time, and resets the current token count if it has -
takeToken
public boolean takeToken()Attempts to take a token, and starts a new window if the bucket was full- Returns:
trueon success;falseif no tokens are available
-
waitAndTakeToken
Takes a token and then runs the specified command. If a token is not available, waits until the next reset, then tries again- Parameters:
command- The command to run on success
-
waitAndRun
Runs the specified command when a token is available, but does not take the token. If a token is not available, waits until the next reset, then tries again- Parameters:
command- The command to run on success
-