Class WindowedRateLimiter

java.lang.Object
com.gmt2001.ratelimiters.WindowedRateLimiter
Direct Known Subclasses:
WindowedSwitchingRateLimiter

public class WindowedRateLimiter extends Object
Handles rate limiting using a window which resets a period of time after the first token is used
Author:
gmt2001
  • Field Details

    • windowMS

      protected final long windowMS
    • limit

      protected final int limit
    • mutex

      protected final Object mutex
    • nextReset

      protected Instant nextReset
    • currentTokens

      protected int currentTokens
  • Constructor Details

    • WindowedRateLimiter

      public WindowedRateLimiter(Duration window, int limit)
      Constructor
      Parameters:
      windowMS - The length of the window
      limit - 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 milliseconds
      limit - 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:
      true if there is a token available
    • currentTokens

      public int currentTokens()
      Returns:
      The current number of tokens available
    • nextReset

      public Instant nextReset()
      Returns:
      An Instant indicating 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:
      true on success; false if no tokens are available
    • waitAndTakeToken

      public void waitAndTakeToken(Runnable command)
      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

      public void waitAndRun(Runnable command)
      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