Class SimpleTimeBasedGuard

java.lang.Object
ch.qos.logback.core.util.SimpleTimeBasedGuard

public class SimpleTimeBasedGuard extends Object
A simple time-based guard that limits the number of allowed operations within a sliding time window. This class is useful for rate limiting or preventing excessive actions over time periods. It supports time injection for testing purposes.
Since:
1.5.22
Author:
Ceki Gülcü
  • Field Details

  • Constructor Details

    • SimpleTimeBasedGuard

      public SimpleTimeBasedGuard(long windowDurationMs, int maxAllows)
      Creates a guard with custom limits.
      Parameters:
      windowDurationMs - how many millis per window (e.g. 30_000 for 30 minutes)
      maxAllows - how many allows per window (e.g. 2)
    • SimpleTimeBasedGuard

      Convenience: uses defaults — 2 allows every 30 minutes
  • Method Details

    • allow

      public boolean allow()
      Checks if an operation is allowed based on the current time window. If allowed, increments the usage count for the current window. If the window has expired, resets the window and allows the operation.
      Returns:
      true if the operation is allowed, false otherwise
    • setCurrentTimeMillis

      public void setCurrentTimeMillis(long timestamp)
      Sets the artificial current time for testing purposes. When set, currentTimeMillis() will return this value instead of System.currentTimeMillis().
      Parameters:
      timestamp - the artificial timestamp in milliseconds
    • clearCurrentTime

      public void clearCurrentTime()
      Clears the artificial time, reverting to using System.currentTimeMillis().
    • getAllowsUsed

      public int getAllowsUsed()
      Returns the number of allows used in the current window.
      Returns:
      the number of allows used
    • getAllowsRemaining

      public int getAllowsRemaining()
      Returns the number of allows remaining in the current window.
      Returns:
      the number of allows remaining
    • getWindowDuration

      public long getWindowDuration()
      Returns the window duration in milliseconds.
      Returns:
      the window duration in milliseconds
    • getMaxAllows

      public int getMaxAllows()
      Returns the maximum number of allows per window.
      Returns:
      the maximum number of allows
    • getMillisUntilNextWindow

      public long getMillisUntilNextWindow()
      Returns the number of milliseconds until the next window starts. If no window has started yet, returns the full window duration.
      Returns:
      milliseconds until next window