Remove most of atomix.utils.*
[controller.git] / third-party / atomix / utils / src / main / java / io / atomix / utils / concurrent / RetryingFunction.java
1 /*
2  * Copyright 2015-present Open Networking Foundation
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.atomix.utils.concurrent;
17
18 import java.util.function.Function;
19
20 import static com.google.common.base.Throwables.throwIfUnchecked;
21
22 /**
23  * Function that retries execution on failure.
24  *
25  * @param <U> input type
26  * @param <V> output type
27  */
28 public class RetryingFunction<U, V> implements Function<U, V> {
29   private final Function<U, V> baseFunction;
30   private final Class<? extends Throwable> exceptionClass;
31   private final int maxRetries;
32   private final int maxDelayBetweenRetries;
33
34   public RetryingFunction(Function<U, V> baseFunction,
35       Class<? extends Throwable> exceptionClass,
36       int maxRetries,
37       int maxDelayBetweenRetries) {
38     this.baseFunction = baseFunction;
39     this.exceptionClass = exceptionClass;
40     this.maxRetries = maxRetries;
41     this.maxDelayBetweenRetries = maxDelayBetweenRetries;
42   }
43
44   @SuppressWarnings("squid:S1181")
45   // Yes we really do want to catch Throwable
46   @Override
47   public V apply(U input) {
48     int retryAttempts = 0;
49     while (true) {
50       try {
51         return baseFunction.apply(input);
52       } catch (Throwable t) {
53         if (!exceptionClass.isAssignableFrom(t.getClass()) || retryAttempts == maxRetries) {
54           throwIfUnchecked(t);
55           throw new RuntimeException(t);
56         }
57         Retries.randomDelay(maxDelayBetweenRetries);
58         retryAttempts++;
59       }
60     }
61   }
62 }