blob: dc82047286397755522533ab68f71fd5b8dbf509 [file] [log] [blame]
Madan Jampania29c6772015-08-17 13:17:07 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
Madan Jampania29c6772015-08-17 13:17:07 -07003 *
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
Madan Jampania29c6772015-08-17 13:17:07 -070018import com.google.common.base.Throwables;
19
Ray Milkey6a51cb92018-03-06 09:03:03 -080020import java.util.function.Function;
21
Madan Jampania29c6772015-08-17 13:17:07 -070022/**
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 Milkeyaef45852016-01-11 17:13:19 -080045 @SuppressWarnings("squid:S1181")
Ray Milkey86f20cc2015-12-09 16:54:09 -080046 // 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) {
Ray Milkey6a51cb92018-03-06 09:03:03 -080055 Throwables.throwIfUnchecked(t);
56 throw new RetriesExceededException(t);
Madan Jampania29c6772015-08-17 13:17:07 -070057 }
58 Tools.randomDelay(maxDelayBetweenRetries);
59 retryAttempts++;
60 }
61 }
62 }
63}