2 * Copyright 2015-present Open Networking Foundation
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package io.atomix.utils.concurrent;
18 import java.util.function.Function;
20 import static com.google.common.base.Throwables.throwIfUnchecked;
23 * Function that retries execution on failure.
25 * @param <U> input type
26 * @param <V> output type
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;
34 public RetryingFunction(Function<U, V> baseFunction,
35 Class<? extends Throwable> exceptionClass,
37 int maxDelayBetweenRetries) {
38 this.baseFunction = baseFunction;
39 this.exceptionClass = exceptionClass;
40 this.maxRetries = maxRetries;
41 this.maxDelayBetweenRetries = maxDelayBetweenRetries;
44 @SuppressWarnings("squid:S1181")
45 // Yes we really do want to catch Throwable
47 public V apply(U input) {
48 int retryAttempts = 0;
51 return baseFunction.apply(input);
52 } catch (Throwable t) {
53 if (!exceptionClass.isAssignableFrom(t.getClass()) || retryAttempts == maxRetries) {
55 throw new RuntimeException(t);
57 Retries.randomDelay(maxDelayBetweenRetries);