Retrier { public <T extends Object> T execute(Retriable retriable) throws Exception { return execute(retriable, DEFAULT_EXCEPTION_HANDLER); } Retrier();  Retrier(int maxRetries);  Retrier(int maxRetries, int waitBetweenRetries, int waitBetweenRetriesMultiplier); T execute(Retriable retriable); T execute(Retriable retriable,
                                        ExceptionHandler exceptionHandler); static final int DEFAULT_MAX_RETRIES; static final int DEFAULT_WAIT_BETWEEN_RETRIES; static final int DEFAULT_WAIT_MULTIPLIER; }
@Test public void testRetrierSuccess() throws Exception { final String expectedResponse = "success!"; String response = null; Retrier retrier = new Retrier(); response = retrier.execute(new Retriable() { @Override public String retry() throws Exception { return expectedResponse; } }); assertEquals(expectedResponse, response); }
@Test public void testRetrierRetry() throws Exception { final int expectedAttempts = 3; final int failuresBeforeSuccess = 2; final RetryTester retryTester = new RetryTester(failuresBeforeSuccess); Retrier retrier = new Retrier(); int actualAttempts = retrier.execute(new Retriable() { @Override public Integer retry() throws Exception { return retryTester.doWork(); } }); assertEquals(expectedAttempts, actualAttempts); }
@Test public void testRetrierFail() throws Exception { final Integer expectedAttempts = 4; final int failuresBeforeSuccess = 4; final RetryTester retryTester = new RetryTester(failuresBeforeSuccess); Retrier retrier = new Retrier(); try { retrier.execute(new Retriable() { @Override public Integer retry() throws Exception { return retryTester.doWork(); } }); } catch (Exception e) { assertEquals(expectedAttempts, Integer.valueOf(e.getMessage())); } }
@Test public void testRetrierExponentiallyIncreasingWaitBetweenRetries() throws Exception { final Integer expectedAttempts = 4; final int failuresBeforeSuccess = 4; final RetryTester retryTester = new RetryTester(failuresBeforeSuccess); Retrier retrier = new Retrier(Retrier.DEFAULT_MAX_RETRIES, 10, 2); long start = System.currentTimeMillis(); try { retrier.execute(new Retriable() { @Override public Integer retry() throws Exception { return retryTester.doWork(); } }); } catch (Exception e) { assertEquals(expectedAttempts, Integer.valueOf(e.getMessage())); long elapsed = System.currentTimeMillis() - start; assertTrue(elapsed >= 130); assertTrue(elapsed < 290); } }