Skip to content

Instantly share code, notes, and snippets.

@RobertFischer
Last active July 25, 2020 22:12
Show Gist options
  • Save RobertFischer/51b3f50c76744cb5ccfc to your computer and use it in GitHub Desktop.
Save RobertFischer/51b3f50c76744cb5ccfc to your computer and use it in GitHub Desktop.
A utility method for retrying on exception, using Java 8 lambdas
public class Retry {
private static final Logger log = Logger.getLogger(Retry.class);
public static interface CallToRetry<T> {
<T> T doIt() throws Exception;
}
public static T withRetry(int maxTimes, long initialWait, int waitMultiplier, CallToRetry<T> call) {
if(maxTimes <= 0) {
throw new IllegalArgumentException("Must run at least one time");
}
if(initialWait <= 0) {
throw new IllegalArgumentException("Initial wait must be at least 1");
}
if(waitMultiplier <= 0) {
throw new IllegalArgumentException("Wait multiplier must be at least 1");
}
if(callToRetry == null) {
throw new IllegalArgumentException("No call to retry provided");
}
Exception thrown = null;
for(int i = 0; i < maxTimes; i++) {
try {
return call();
} catch(Exception e) {
thrown = e;
log.info("Encountered failure on " + callToRetry + ", attempt " + (i+1) + " of " + maxTimes, e);
}
try {
Thread.sleep(initialWait + (waitMultiplier * i));
} catch(InterruptedException wakeAndAbort){
break;
}
}
if(thrown == null) {
throw new IllegalStateException("Failure calling " + callToRetry + ", but no thrown exception found!");
}
throw thrown;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment