blob: 1e320533dbda6765748f434182ff3842ee00fa5a [file] [log] [blame]
Madan Jampania29c6772015-08-17 13:17:07 -07001/*
2 * Copyright 2015 Open Networking Laboratory
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 */
16package org.onlab.util;
17
18import java.util.function.Function;
19
20import com.google.common.base.Throwables;
21
22/**
23 * Function that retries execution on failure.
24 *
25 * @param <U> input type
26 * @param <V> output type
27 */
28public class RetryingFunction<U, V> implements Function<U, V> {
29
30 private final Function<U, V> baseFunction;
31 private final Class<? extends Throwable> exceptionClass;
32 private final int maxRetries;
33 private final int maxDelayBetweenRetries;
34
35 public RetryingFunction(Function<U, V> baseFunction,
36 Class<? extends Throwable> exceptionClass,
37 int maxRetries,
38 int maxDelayBetweenRetries) {
39 this.baseFunction = baseFunction;
40 this.exceptionClass = exceptionClass;
41 this.maxRetries = maxRetries;
42 this.maxDelayBetweenRetries = maxDelayBetweenRetries;
43 }
44
Ray Milkey86f20cc2015-12-09 16:54:09 -080045 @SuppressWarnings("squid:S1181")
46 // Yes we really do want to catch Throwable
Madan Jampania29c6772015-08-17 13:17:07 -070047 @Override
48 public V apply(U input) {
49 int retryAttempts = 0;
50 while (true) {
51 try {
52 return baseFunction.apply(input);
53 } catch (Throwable t) {
54 if (!exceptionClass.isAssignableFrom(t.getClass()) || retryAttempts == maxRetries) {
55 Throwables.propagate(t);
56 }
57 Tools.randomDelay(maxDelayBetweenRetries);
58 retryAttempts++;
59 }
60 }
61 }
62}