Class RateLimiter

java.lang.Object
com.oorian.security.RateLimiter

public class RateLimiter extends Object
A fixed-window rate limiter for throttling requests per session.

Tracks the number of requests within a configurable time window and rejects requests that exceed the configured maximum. When the window expires, the counter resets automatically.

This class is thread-safe. All mutating operations are synchronized.

Usage:


 RateLimiter limiter = new RateLimiter(100, 60000); // 100 requests per minute

 if (limiter.tryAcquire())
 {
     // Process the request
 }
 else
 {
     // Reject: rate limit exceeded
 }
 
Since:
2.1
Version:
1.0
Author:
Marvin P. Warble Jr.
  • Constructor Summary

    Constructors
    Constructor
    Description
    RateLimiter(int maxRequests, long windowMillis)
    Creates a new RateLimiter with the specified limits.
  • Method Summary

    Modifier and Type
    Method
    Description
    int
    Returns the number of remaining requests allowed in the current window.
    void
    Resets the rate limiter, clearing the current window and count.
    boolean
    Attempts to acquire a permit for one request.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • RateLimiter

      public RateLimiter(int maxRequests, long windowMillis)
      Creates a new RateLimiter with the specified limits.
      Parameters:
      maxRequests - the maximum number of requests allowed per window
      windowMillis - the time window duration in milliseconds
  • Method Details

    • tryAcquire

      public boolean tryAcquire()
      Attempts to acquire a permit for one request.

      If the current time window has expired, the counter resets before checking. Returns true if the request is within the rate limit, false if the limit has been exceeded.

      Returns:
      true if the request is allowed, false if rate limited
    • getRemainingRequests

      public int getRemainingRequests()
      Returns the number of remaining requests allowed in the current window.
      Returns:
      the number of remaining requests, or 0 if the limit has been reached
    • reset

      public void reset()
      Resets the rate limiter, clearing the current window and count.