All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.castled.utils.RetryUtils Maven / Gradle / Ivy

There is a newer version: 1.0.0
Show newest version
package io.castled.utils;

import io.castled.core.WaitTimeAndRetry;
import io.castled.exceptions.CastledRuntimeException;
import io.castled.functionalinterfaces.ThrowingSupplier;

import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class RetryUtils {

    public static  T retrySupplier(ThrowingSupplier supplier, int maxRetries,
                                      List> whitelistedExceptions, BiFunction actionOnError) throws Exception {
        for (int attempts = 0; attempts <= maxRetries; attempts++) {
            try {
                return supplier.get();
            } catch (Throwable e) {
                WaitTimeAndRetry waitTimeAndRetry = actionOnError.apply(e, attempts);
                if (!waitTimeAndRetry.isShouldRetry()) {
                    throw e;
                }
                if (attempts == maxRetries || !isExceptionWhitelisted(whitelistedExceptions, e)) {
                    throw e;
                }
                ThreadUtils.interruptIgnoredSleep(waitTimeAndRetry.getWaitTimeMs());
            }
        }
        throw new CastledRuntimeException("cannot reach here");
    }

    public static boolean isExceptionWhitelisted(List> whitelistedExceptions, Throwable exception) {
        for (final Class type : whitelistedExceptions) {
            if (type.isAssignableFrom(exception.getClass())) {
                return true;
            }
        }
        return false;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy