Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Generic method providing 'retry operation' capabilities.
- */
- public final class Retry {
- private static final String DEFAULT_ERROR_MESSAGE = "Retries exhausted";
- public static <Result> Result retry(int times,
- Function0<Result> operation,
- Function1<Result, Boolean> checker,
- Function0<Void> preRetry,
- String errorMessage) throws Exception {
- Result operationResult = null;
- Exception operationException = null;
- try {
- operationResult = operation.apply();
- } catch (Exception e) {
- operationException = e;
- }
- final Result result;
- if (operationException == null && checker.apply(operationResult)) {
- result = operationResult;
- } else {
- if (times > 0) {
- if (preRetry != null) {
- preRetry.apply();
- }
- result = retry(
- times - 1, operation, checker, preRetry, errorMessage);
- } else {
- String message = errorMessage != null ? errorMessage : DEFAULT_ERROR_MESSAGE;
- throw operationException != null ? operationException : new Exception(message);
- }
- }
- return result;
- }
- private Retry() {
- // cannot instatiate
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment