Created
May 25, 2017 18:29
-
-
Save davidpelfree/2b42d7f5bb49b707e0d161dd5509ba7d to your computer and use it in GitHub Desktop.
Java 8 retry pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package util; | |
import java.util.Arrays; | |
import java.util.function.Supplier; | |
public final class Util { | |
/** | |
* Retry to run a function a few times, retry if specific exceptions occur. | |
* | |
* @param timeoutExceptionClasses what exceptions should lead to retry. Default: any exception | |
*/ | |
public static <T> T retry(Supplier<T> function, int maxRetries, Class<? extends Exception>... timeoutExceptionClasses) { | |
timeoutExceptionClasses = timeoutExceptionClasses.length == 0 ? new Class[]{Exception.class} : timeoutExceptionClasses; | |
int retryCounter = 0; | |
Exception lastException = null; | |
while (retryCounter < maxRetries) { | |
try { | |
return function.get(); | |
} catch (Exception e) { | |
lastException = e; | |
if (Arrays.stream(timeoutExceptionClasses).noneMatch(tClass -> | |
tClass.isAssignableFrom(e.getClass()) | |
)) | |
throw lastException instanceof RuntimeException ? | |
((RuntimeException) lastException) : | |
new RuntimeException(lastException); | |
else { | |
retryCounter++; | |
System.err.println("FAILED - Command failed on retry " + retryCounter + " of " + maxRetries); | |
e.printStackTrace(); | |
if (retryCounter >= maxRetries) { | |
break; | |
} | |
} | |
} | |
} | |
throw lastException instanceof RuntimeException ? | |
((RuntimeException) lastException) : | |
new RuntimeException(lastException); | |
} | |
/** Manual test method */ | |
public static void main(String... args) throws Exception { | |
retry(() -> { | |
System.out.println(5 / 0); | |
return null; | |
}, 5, Exception.class); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment