Automatic retry on failure


What the need?
To make processing more robust and less prone to failure, sometimes it helps to automatically retry a failed operation in case it might succeed on a subsequent attempt. For example a call to a web service that fails because of a network glitch or a DeadLockLoserException in a database update may resolve themselves after a short wait. 
So, how to...?
To automate the retry of such operations the Spring team developped a retry module in Spring Batch under the package org.springframework.batch.retry. 
From the doc: Client code is not aware of the details of when and how many times to retry the operation, and various strategies for those details are available. The decision about whether to retry or abandon lies with the Framework, but is parameterisable through some retry meta data.Retryable operations are usually transactional, but this can be provided by a normal transaction template or interceptor (transaction meta data are independent of the retry meta data).
Since some months, these classes are available in a dedicated project on Github.
So, to begin, add this dependency in your pom.xml: 

<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.0.0.RELEASE</version>
</dependency>



Then, if you want to handle exceptions, you just have to use the RetryTemplate:
RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(new TimeoutRetryPolicy(30000L));
Foo result = template.execute(new RetryCallback<Foo>() {
    public Foo doWithRetry(RetryContext context) {
        // Do stuff that might fail, e.g. webservice operation
        return result;
    }
});
Inside a RetryTemplate the decision to retry or fail in the execute method is determined by a RetryPolicy:
RetryPolicy retryPolicy = new SimpleRetryPolicy(3, Collections.<Class<? extends Throwable>, Boolean> singletonMap(SocialException.class, true));
retryTemplate = new RetryTemplate();
retryTemplate.setRetryPolicy(retryPolicy);


In this case, all the exceptions extending SocialException will be retried 3 times max.
Enjoy!
Source:
https://github.com/Springsource/spring-retry
http://static.springsource.org/spring-batch/cases/retry.html