View Javadoc

1   /*
2      Copyright 2010 Atlassian
3   
4      Licensed under the Apache License, Version 2.0 (the "License");
5      you may not use this file except in compliance with the License.
6      You may obtain a copy of the License at
7   
8          http://www.apache.org/licenses/LICENSE-2.0
9   
10     Unless required by applicable law or agreed to in writing, software
11     distributed under the License is distributed on an "AS IS" BASIS,
12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13     See the License for the specific language governing permissions and
14     limitations under the License.
15   */
16  package io.atlassian.fugue.retry;
17  
18  /**
19   * A backoff task for use in a retry -function, -supplier, or -task. This should
20   * be used as the beforeRetry hook. Upon each execution, the amount of time to
21   * wait before retrying the function call is doubled.
22   *
23   * This class maintains an internal state; we recommend creating a new instance
24   * for each use.
25   *
26   */
27  public class BeforeRetryExponentialBackoffTask implements Runnable {
28    private long backoff;
29  
30    /**
31     * <p>
32     * Constructor for BeforeRetryExponentialBackoffTask.
33     * </p>
34     *
35     * @param backoffMillis the amount of time to wait, in milliseconds before
36     * retrying the first time. This is doubled for each subsequent retry. This
37     * parameter must be above zero.
38     */
39    public BeforeRetryExponentialBackoffTask(long backoffMillis) {
40      if (backoffMillis <= 0) {
41        throw new IllegalArgumentException("Backoff time must not be negative.");
42      }
43      this.backoff = backoffMillis;
44    }
45  
46    /**
47     * This method causes the current thread to sleep for a duration which doubles
48     * after each successive call. InterruptedExceptions are wrapped before being
49     * rethrown in a RuntimeException.
50     */
51    public void run() {
52      try {
53        Thread.sleep(backoff);
54        backoff = backoff * 2;
55      } catch (InterruptedException e) {
56        throw new RuntimeException(e);
57      }
58    }
59  
60    long currentBackoff() {
61      return backoff;
62    }
63  }