Madan Jampani | a29c677 | 2015-08-17 13:17:07 -0700 | [diff] [blame] | 1 | /* |
Brian O'Connor | 5ab426f | 2016-04-09 01:19:45 -0700 | [diff] [blame] | 2 | * Copyright 2015-present Open Networking Laboratory |
Madan Jampani | a29c677 | 2015-08-17 13:17:07 -0700 | [diff] [blame] | 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 | */ |
| 16 | package org.onlab.util; |
| 17 | |
| 18 | import java.util.function.Function; |
| 19 | |
| 20 | import 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 | */ |
| 28 | public 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 Milkey | aef4585 | 2016-01-11 17:13:19 -0800 | [diff] [blame] | 45 | @SuppressWarnings("squid:S1181") |
Ray Milkey | 86f20cc | 2015-12-09 16:54:09 -0800 | [diff] [blame] | 46 | // Yes we really do want to catch Throwable |
Madan Jampani | a29c677 | 2015-08-17 13:17:07 -0700 | [diff] [blame] | 47 | @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 | } |