Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   * Copyright 2012-2015, Inc. or its affiliates. All Rights Reserved.
   * Licensed under the Apache License, Version 2.0 (the "License").
   * You may not use this file except in compliance with the License.
   * A copy of the License is located at
  * or in the "license" file accompanying this file. This file is distributed
  * express or implied. See the License for the specific language governing
  * permissions and limitations under the License.
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 {
         // some code that can fail and should be throttled
     catch (Exception e) {

 public class BackoffThrottler {
     private final long initialSleep;
     private final long maxSleep;
     private final double backoffCoefficient;
     private final AtomicLong failureCount = new AtomicLong();

Construct an instance of the throttler.

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.
     public BackoffThrottler(long initialSleeplong maxSleepdouble backoffCoefficient) {
         this. = initialSleep;
         this. = maxSleep;
         this. = backoffCoefficient;
     private long calculateSleepTime() {
         double sleepMillis = (Math.pow(.get() - 1)) * ;
         return Math.min((longsleepMillis);

Sleep if there were failures since the last success call.

     public void throttle() throws InterruptedException {
         if (.get() > 0) {

Resent failure count to 0.
     public void success() {

Increment failure count.
     public void failure() {
New to GrepCode? Check out our FAQ X