Wednesday, July 24, 2013

Asynchronous retry pattern

0 comments
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); 

You can now run arbitrary block of code and the library will retry it for you in case it throws

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

Leave a Reply

 
All Tech News IN © 2011 DheTemplate.com & Main Blogger .