Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@davidpelfree
Created May 25, 2017 18:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save davidpelfree/2b42d7f5bb49b707e0d161dd5509ba7d to your computer and use it in GitHub Desktop.
Save davidpelfree/2b42d7f5bb49b707e0d161dd5509ba7d to your computer and use it in GitHub Desktop.
Java 8 retry pattern
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