blob: bb07c1228f7974b8b4da2d6e84a6b6492dfffdc1 [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
Ray Milkey9f87e512016-01-05 10:00:22 -080022import static org.onlab.util.SonarSuppressionConstants.SONAR_CATCH_THROWABLE;
23
Madan Jampania29c6772015-08-17 13:17:07 -070024/**
25 * Function that retries execution on failure.
26 *
27 * @param <U> input type
28 * @param <V> output type
29 */
30public class RetryingFunction<U, V> implements Function<U, V> {
31
32 private final Function<U, V> baseFunction;
33 private final Class<? extends Throwable> exceptionClass;
34 private final int maxRetries;
35 private final int maxDelayBetweenRetries;
36
37 public RetryingFunction(Function<U, V> baseFunction,
38 Class<? extends Throwable> exceptionClass,
39 int maxRetries,
40 int maxDelayBetweenRetries) {
41 this.baseFunction = baseFunction;
42 this.exceptionClass = exceptionClass;
43 this.maxRetries = maxRetries;
44 this.maxDelayBetweenRetries = maxDelayBetweenRetries;
45 }
46
Ray Milkey9f87e512016-01-05 10:00:22 -080047 @SuppressWarnings(SONAR_CATCH_THROWABLE)
Ray Milkey86f20cc2015-12-09 16:54:09 -080048 // Yes we really do want to catch Throwable
Madan Jampania29c6772015-08-17 13:17:07 -070049 @Override
50 public V apply(U input) {
51 int retryAttempts = 0;
52 while (true) {
53 try {
54 return baseFunction.apply(input);
55 } catch (Throwable t) {
56 if (!exceptionClass.isAssignableFrom(t.getClass()) || retryAttempts == maxRetries) {
57 Throwables.propagate(t);
58 }
59 Tools.randomDelay(maxDelayBetweenRetries);
60 retryAttempts++;
61 }
62 }
63 }
64}