Bohtvaroh

Blogger - FPOWJPWB - Retry

Jul 26th, 2012
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.47 KB | None | 0 0
  1. /**
  2.  * Generic method providing 'retry operation' capabilities.
  3.  */
  4. public final class Retry {
  5.     private static final String DEFAULT_ERROR_MESSAGE = "Retries exhausted";
  6.  
  7.     public static <Result> Result retry(int times,
  8.                                         Function0<Result> operation,
  9.                                         Function1<Result, Boolean> checker,
  10.                                         Function0<Void> preRetry,
  11.                                         String errorMessage) throws Exception {
  12.         Result operationResult = null;
  13.         Exception operationException = null;
  14.         try {
  15.             operationResult = operation.apply();
  16.         } catch (Exception e) {
  17.             operationException = e;
  18.         }
  19.  
  20.         final Result result;
  21.         if (operationException == null && checker.apply(operationResult)) {
  22.             result = operationResult;
  23.         } else {
  24.             if (times > 0) {
  25.                 if (preRetry != null) {
  26.                     preRetry.apply();
  27.                 }
  28.                 result = retry(
  29.                         times - 1, operation, checker, preRetry, errorMessage);
  30.             } else {
  31.                 String message = errorMessage != null ? errorMessage : DEFAULT_ERROR_MESSAGE;
  32.                 throw operationException != null ? operationException : new Exception(message);
  33.             }
  34.         }
  35.  
  36.         return result;
  37.     }
  38.  
  39.     private Retry() {
  40.         // cannot instatiate
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment