Class BackoffThrottler


  • @NotThreadSafe
    public final class BackoffThrottler
    extends java.lang.Object
    Used to throttle code execution in presence of failures using exponential backoff logic. The formula used to calculate the next sleep interval is:

     min(pow(backoffCoefficient, failureCount - 1) * initialSleep, maxSleep);
     

    Example usage:

    
     BackoffThrottler throttler = new BackoffThrottler(1000, 60000, 2);
     while(!stopped) {
         try {
             long throttleMs = throttler.getSleepTime();
             if (throttleMs > 0) {
                 Thread.sleep(throttleMs);
             }
             // some code that can fail and should be throttled
             ...
             throttler.success();
         }
         catch (Exception e) {
             throttler.failure();
         }
     }
     
    • Constructor Summary

      Constructors 
      Constructor Description
      BackoffThrottler​(java.time.Duration initialSleep, java.time.Duration maxSleep, double backoffCoefficient)
      Construct an instance of the throttler.
    • Constructor Detail

      • BackoffThrottler

        public BackoffThrottler​(java.time.Duration initialSleep,
                                @Nullable
                                java.time.Duration maxSleep,
                                double backoffCoefficient)
        Construct an instance of the throttler.
        Parameters:
        initialSleep - time to sleep on the first failure
        maxSleep - maximum time to sleep independently of number of failures
        backoffCoefficient - coefficient used to calculate the next time to sleep.
    • Method Detail

      • getSleepTime

        public long getSleepTime()
      • getAttemptCount

        public int getAttemptCount()
      • success

        public void success()
        Reset failure count to 0.
      • failure

        public void failure()
        Increment failure count.