When you have a piece of code that often fails and must be retried, this Java 7/8 library provides rich and unobtrusive API with fast and scalable solution to this problem:



ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); RetryExecutor executor = new AsyncRetryExecutor(scheduler). retryOn(SocketException.class). withExponentialBackoff(500, 2). //500ms times 2 after each retry withMaxDelay(10_000). //10 seconds withUniformJitter(). //add between +/- 100 ms randomly withMaxRetries(20);

SocketException

final CompletableFuture<Socket> future = executor.getWithRetry(() -> new Socket("localhost", 8080) ); future.thenAccept(socket -> System.out.println("Connected! " + socket) );

getWithRetry()

CompletableFuture

Future

localhost:8080

SocketException

executor. getWithRetry(() -> new Socket("localhost", 8080)). thenAccept(socket -> System.out.println("Connected! " + socket));

TRACE | Retry 0 failed after 3ms, scheduled next retry in 508ms (Sun Jul 21 21:01:12 CEST 2013) java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0-ea] //... TRACE | Retry 1 failed after 0ms, scheduled next retry in 934ms (Sun Jul 21 21:01:13 CEST 2013) java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0-ea] //... TRACE | Retry 2 failed after 0ms, scheduled next retry in 1919ms (Sun Jul 21 21:01:15 CEST 2013) java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0-ea] //... TRACE | Successful after 2 retries, took 0ms and returned: Socket[addr=localhost/127.0.0.1,port=8080,localport=46332] Connected! Socket[addr=localhost/127.0.0.1,port=8080,localport=46332]





CompletableFuture<String> stringFuture = executor.getWithRetry(ctx -> unreliable()); CompletableFuture<Integer> intFuture = executor.getWithRetry(ctx -> slow()); stringFuture.thenAcceptBoth(intFuture, (String s, Integer i) -> { //both done after some retries });

thenAcceptBoth()

CompletableFuture.acceptEither()

Rationale

public interface RetryExecutor { CompletableFuture<Void> doWithRetry(RetryRunnable action); <V> CompletableFuture<V> getWithRetry(Callable<V> task); <V> CompletableFuture<V> getWithRetry(RetryCallable<V> task); <V> CompletableFuture<V> getFutureWithRetry(RetryCallable<CompletableFuture<V>> task); }

CompletableFuture

.get()

Future

Basic API

RetryExecutor executor = //... executor.getWithRetry(() -> new Socket("localhost", 8080));

CompletableFuture<Socket>

localhost:8080

executor. getWithRetry(ctx -> new Socket("localhost", 8080 + ctx.getRetryCount())). thenAccept(System.out::println);

ctx.getRetryCount()

0

localhost:8080

localhost:8081

8080 + 1

Arrays.asList("host-one", "host-two", "host-three"). stream(). forEach(host -> executor. getWithRetry(ctx -> new Socket(host, 8080 + ctx.getRetryCount())). thenAccept(System.out::println) );

RetryExecutor

getFutureWithRetry()

CompletableFuture<V>

private CompletableFuture<String> asyncHttp(URL url) { /*...*/} //... final CompletableFuture<CompletableFuture<String>> response = executor.getWithRetry(ctx -> asyncHttp(new URL("http://example.com")));

asyncHttp()

getWithRetry()

CompletableFuture<CompletableFuture<V>>

asyncHttp()

CompletableFuture<String>

final CompletableFuture<String> response = executor.getFutureWithRetry(ctx -> asyncHttp(new URL("http://example.com")));

RetryExecutor

asyncHttp()

Future

Configuration Options

RetryExecutor

Throwable

Creating an Instance of RetryExecutor

RetryExecutor

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); RetryExecutor executor = new AsyncRetryExecutor(scheduler); //... scheduler.shutdownNow();

AsyncRetryExecutor

ScheduledExecutorService

AsyncRetryExecutor

with*()

executor

RetryExecutor

Retrying Policy

Exceptions

Throwable

AbortRetryException

executor. retryOn(OptimisticLockException.class). withNoDelay(). getWithRetry(ctx -> dao.optimistic());

dao.optimistic()

OptimisticLockException

Throwable

retryOn()

executor.retryOn(Exception.class)

executor. abortOn(NullPointerException.class). abortOn(IllegalArgumentException.class). getWithRetry(ctx -> dao.optimistic());

NullPointerException

IllegalArgumentException

retryOn()

abortOn()

IOException

SQLException

FileNotFoundException

java.sql.DataTruncation

executor. retryOn(IOException.class). abortIf(FileNotFoundException.class). retryOn(SQLException.class). abortIf(DataTruncation.class). getWithRetry(ctx -> dao.load(42));

executor. abortIf(throwable -> throwable instanceof SQLException && throwable.getMessage().contains("ORA-00911") );

Max Number of Retries

executor.withMaxRetries(5)

executor.dontRetry()

Delays Between Retries (backoff)

OptimisticLockException

should we retry with constant intervals or increase delay after each failure?





should there be a lower and upper limit on waiting time?





should we add random “jitter” to delay times to spread retries of many tasks in time?





Fixed Interval Between Retries

executor.withFixedBackoff(200)

RetryExecutor

fixedRate

executor. withFixedBackoff(200). withFixedRate()

RetryExecutor

ScheduledExecutorService

Exponentially Growing Intervals Between Retries

executor.withExponentialBackoff(100, 2)

executor. withExponentialBackoff(100, 2). withMaxDelay(10_000) //10 seconds

Random Jitter

executor.withUniformJitter(100) //ms

executor.withProportionalJitter(0.1) //10%

executor.withMinDelay(50) //ms

Implementation Details

CompletableFuture

ScheduledExecutorService

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); AsyncRetryExecutor first = new AsyncRetryExecutor(scheduler). retryOn(Exception.class). withExponentialBackoff(500, 2); AsyncRetryExecutor second = first.abortOn(FileNotFoundException.class); AsyncRetryExecutor third = second.withMaxRetries(10);

with*()

retryOn()

abortOn()

first

FileNotFoundException

second

third

scheduler

AsyncRetryExecutor

ScheduledExecutorService

close()

AsyncRetryExecutor

when writing a concurrent code immutability can greatly reduce risk of multi-threading bugs. For example RetryContext holds number of retries. But instead of mutating it we simply create new instance (copy) with incremented but final counter. No race condition or visibility can ever occur.





holds number of retries. But instead of mutating it we simply create new instance (copy) with incremented but counter. No race condition or visibility can ever occur. if you are given an existing RetryExecutor which is almost exactly what you want but you need one minor tweak, you simply call executor.with...() and get a fresh copy. You don’t have to worry about other places where the same executor was used (see: Spring integration for further examples)





which is almost exactly what you want but you need one minor tweak, you simply call and get a fresh copy. You don’t have to worry about other places where the same executor was used (see: for further examples) functional programming and immutable data structures are sexy these days ;-).





AsyncRetryExecutor

final

Dependencies

Spring Integration

RetryExecutor

<property name="..."/>

@Autowired private TransactionTemplate template;

final int oldTimeout = template.getTimeout(); template.setTimeout(10_000); //do the work template.setTimeout(oldTimeout);

oldTimeout

finally

TransactionTemplate

private timeout

volatile

@Configuration class Beans { @Bean public RetryExecutor retryExecutor() { return new AsyncRetryExecutor(scheduler()). retryOn(SocketException.class). withExponentialBackoff(500, 2); } @Bean(destroyMethod = "shutdownNow") public ScheduledExecutorService scheduler() { return Executors.newSingleThreadScheduledExecutor(); } }

final ApplicationContext context = new AnnotationConfigApplicationContext(Beans.class); final RetryExecutor executor = context.getBean(RetryExecutor.class); //... context.close();

Maturity