blob: 484e236f3c8ec11d64da0f88262b5035bb5d393a [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
45 @Override
46 public V apply(U input) {
47 int retryAttempts = 0;
48 while (true) {
49 try {
50 return baseFunction.apply(input);
51 } catch (Throwable t) {
52 if (!exceptionClass.isAssignableFrom(t.getClass()) || retryAttempts == maxRetries) {
53 Throwables.propagate(t);
54 }
55 Tools.randomDelay(maxDelayBetweenRetries);
56 retryAttempts++;
57 }
58 }
59 }
60}