2 * Copyright 2017-present Open Networking Foundation
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package io.atomix.utils.concurrent;
18 import java.util.concurrent.ThreadLocalRandom;
19 import java.util.function.Function;
20 import java.util.function.Supplier;
25 public final class Retries {
28 * Returns a function that retries execution on failure.
29 * @param base base function
30 * @param exceptionClass type of exception for which to retry
31 * @param maxRetries max number of retries before giving up
32 * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from
33 * the interval (0, maxDelayBetweenRetries]
35 * @param <U> type of function input
36 * @param <V> type of function output
38 public static <U, V> Function<U, V> retryable(Function<U, V> base,
39 Class<? extends Throwable> exceptionClass,
41 int maxDelayBetweenRetries) {
42 return new RetryingFunction<>(base, exceptionClass, maxRetries, maxDelayBetweenRetries);
46 * Returns a Supplier that retries execution on failure.
47 * @param base base supplier
48 * @param exceptionClass type of exception for which to retry
49 * @param maxRetries max number of retries before giving up
50 * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from
51 * the interval (0, maxDelayBetweenRetries]
53 * @param <V> type of supplied result
55 public static <V> Supplier<V> retryable(Supplier<V> base,
56 Class<? extends Throwable> exceptionClass,
58 int maxDelayBetweenRetries) {
59 return () -> new RetryingFunction<>(v -> base.get(),
62 maxDelayBetweenRetries).apply(null);
66 * Suspends the current thread for a random number of millis between 0 and
67 * the indicated limit.
69 * @param ms max number of millis
71 public static void randomDelay(int ms) {
73 Thread.sleep(ThreadLocalRandom.current().nextInt(ms));
74 } catch (InterruptedException e) {
75 throw new RuntimeException("Interrupted", e);
80 * Suspends the current thread for a specified number of millis and nanos.
82 * @param ms number of millis
83 * @param nanos number of nanos
85 public static void delay(int ms, int nanos) {
87 Thread.sleep(ms, nanos);
88 } catch (InterruptedException e) {
89 throw new RuntimeException("Interrupted", e);