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 current thread
21   * sleeps for the time specified at construction.
22   *
23   * This class is thread safe and contains no internal state, hence instances can
24   * be reused and the same instance can be used on multiple threads.
25   *
26   */
27  public class BeforeRetryLinearBackoffTask implements Runnable {
28    private final long backoff;
29  
30    /**
31     * <p>
32     * Constructor for BeforeRetryLinearBackoffTask.
33     * </p>
34     *
35     * @param backoffMillis the time to wait whenever run is executed
36     */
37    public BeforeRetryLinearBackoffTask(long backoffMillis) {
38      if (backoffMillis <= 0) {
39        throw new IllegalArgumentException("Backoff time must not be negative.");
40      }
41      this.backoff = backoffMillis;
42    }
43  
44    /**
45     * This method causes the current thread to sleep for the time specified when
46     * the instance is constructed. InterruptedExceptions are wrapped before being
47     * rethrown in a RuntimeException.
48     */
49    public void run() {
50      try {
51        Thread.sleep(backoff);
52      } catch (InterruptedException e) {
53        throw new RuntimeException(e);
54      }
55    }
56  
57    long currentBackoff() {
58      return backoff;
59    }
60  }