Skip to content
James Hu edited this page Aug 9, 2015 · 7 revisions

Overview

It makes retrying the execution of a Runnable, Callable, or any lambda expression easier. Below are some examples showing how easy it is to use AttemptStrategy:

  new AttemptStrategy()
    .withBackoffStrategy(BackoffStrategies.fixedBackoff(1, TimeUnit.MINUTES))
    .retryIfException(IllegalStateException.class)
    .retryIfException(StorageException.class, e->e.getHttpStatusCode() == 412)
    .run(()->operation1());
  Integer result = new AttemptStrategy()
    .withBackoffStrategy(BackoffStrategies.fibonacciBackoff(1000L, 1, TimeUnit.MINUTES))
    .retryIfException(StorageException.class, e->e.getHttpStatusCode() == 412)
    .retryIfResultEquals(Integer.valueOf(-1))
    .call(()->operation2());
static public boolean createIfNotExist(CloudTableClient tableClient, 
      String tableName, AttemptStrategy attemptStrategy) 
      throws URISyntaxException, StorageException {
  CloudTable table = tableClient.getTableReference(tableName);
  return ExceptionUncheckUtility.getThrowingUnchecked(()->{
    return new AttemptStrategy(attemptStrategy)
      .retryIfException(StorageException.class, 
          e-> e.getHttpStatusCode() == 409)
      .call(()-> table.createIfNotExists());
  });
}

Details

History

The code was based on guava-retrying and the following enhancement had been made:

  • It is now Java 8 native in terms of the usage of java.util.function.* and java.time.*, and support of lambda expression.
  • There is now no separation of a builder and a retryer, every use case now can start with new AttemptStrategy(...) or AttemptStrategy.create(...) (See Constructing AttemptStrategy).
  • There are separate methods accepting Runnable and Callable.
  • More options for exception propagation.
  • More flexible
  • "Attempt" is a better name than "retry", "BackoffStrategy" (for deciding how long to wait before next attempt) is a better name than "WaitStrategy", and "WaitStrategy" (for deciding how to wait for a specified time duration) is a better name than "BlockStrategy"

However, the design in guava-retrying on the separation of backoff strategy, stop strategy, and wait strategy is the foundation. It is a very good modelling of the problem domain. After the overhaul mentioned above, more than 70% of the code are new.