Thursday, December 22, 2016

Asynchronous retry pattern with Java7 / Java8

A piece of code that often fails and must be retried, this Java 7/8 library provides an API. If you want to run arbitrary block of code then the library will retry it for you in case it throws.

Maven

Java 8 library is available in Maven Central Repository:
<dependency>
    <groupId>com.nurkiewicz.asyncretry</groupId>
    <artifactId>asyncretry</artifactId>
    <version>0.0.5</version>
</dependency>

Java 7 library is available in Maven Central Repository:
<dependency>
    <groupId>com.nurkiewicz.asyncretry</groupId>
    <artifactId>asyncretry-jdk7</artifactId>
    <version>0.0.6</version>
</dependency>

Create scheduler and executor for both Java 7 and Java 8. It will listen on the port 2775. If there is an SocketException, then it will retry internally  with maximum no of tries 3 and initial delay 500 ms. Next retry delay with 500 * 2 ms, then 1000 * 2 ms.  And also maximum delay will be 10000 ms.

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

Retry with Java 8 :
final CompletableFuture<Socket> future = executor.getWithRetry(() ->
      new Socket("localhost", 2775)
);

future.thenAccept(socket ->
      System.out.println("Connected! " + socket)
);

Retry with Java 7

final ListenableFuture future = executor.doWithRetry(new RetryRunnable() {
    @Override
    public void run(RetryContext retryContext) throws Exception {
        new Socket("localhost", 2775);
    }
});


No comments:

Post a Comment