12

We decided on using optimistic locking in our web application in order to increase concurrency and without the using of pessimistic locking.

We are now on a lookout for retry solutions.

We would like to have as little impact as possible to our current code base.

One of the solutions we saw on the web is using a retry interceptor with annotation to mark a method as retry able.

Problem is we would like to annotate methods that are having the @Transactional annotation on them but the interceptor fails to retry them for some reason. (the interceptor retries non transactional methods perfectly.)

So:

1) Are there any alternatives for the retry that will have minimum impact on our code?

2) Are there any documentations \ tutorials for that solution?

3) Is it even possible to retry a @Transactional annotated method?

Cheers!

Urbanleg
  • 6,252
  • 16
  • 76
  • 139

3 Answers3

10

Ad 3.

You can use Spring Retry to retry transacted method when a version number or timestamp check failed (optimistic lock occurs).

Configuration

@Configuration
@EnableRetry
public class RetryConfig {

}

Usage

@Retryable(StaleStateException.class)
@Transactional
public void doSomethingWithFoo(Long fooId){
    // read your entity again before changes!
    Foo foo = fooRepository.findOne(fooId);

    foo.setStatus(REJECTED)  // <- sample foo modification

} // commit on method end

Use @Transactional (propagation = Propagation.REQUIRES_NEW) for retrying only the code from annotated method.

mrinal
  • 375
  • 3
  • 15
MariuszS
  • 30,646
  • 12
  • 114
  • 155
2

You have two ways to achieve this as follows

Recovering from hibernate optimistic locking exception

OR

Using Spring AOP to Retry Failed Idempotent Concurrent Operations

hope this will help you..!

Community
  • 1
  • 1
Ashish Jagtap
  • 2,799
  • 3
  • 30
  • 45
  • Ashish, we already tried the second solution, apperantly it is not working when you use it on Transactional methods, do you have any idea why? – Urbanleg Feb 10 '14 at 10:52
  • I followed exactly what is being written in http://josiahgore.blogspot.in/2011/02/using-spring-aop-to-retry-failed.html and then i annotated a service method with @RetryConcurrentOperation(exception = HibernateOptimisticLockingFailureException.class, retries = 12) Now, because the method is annotated with @Transactional it doesnt work, it gives a regular optimistic lock exception, on a non transactional method if i annotate it - it works. – Urbanleg Feb 10 '14 at 11:09
0

The reason your retry cannot work is that @Transactional priority is higher than @Aspect.

You should make @Aspect higher priority by implementing Ordered in TryAgainAspect class

Interceptor class:

@Aspect
@Component
public class TryAgainAspect implements Ordered {

private int maxRetries;
private int order = 1;

public void setMaxRetries(int maxRetries) {
    this.maxRetries = maxRetries;
}

public int getOrder() {
    return this.order;
}

@Pointcut("@annotation(IsTryAgain)")
public void retryOnOptFailure() {
}

@Around("retryOnOptFailure()")
public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
    MethodSignature msig = (MethodSignature) pjp.getSignature();
    Object target = pjp.getTarget();
    Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
    IsTryAgain annotation = currentMethod.getAnnotation(IsTryAgain.class);
    this.setMaxRetries(annotation.tryTimes());

    int numAttempts = 0;
    do {
        numAttempts++;
        try {
            return pjp.proceed();
        } catch (ObjectOptimisticLockingFailureException | StaleObjectStateException exception) {
            exception.printStackTrace();
            if (numAttempts > maxRetries) {
                throw new NoMoreTryException("System error, all retry failed");
            } else {
                System.out.println("0 === retry ===" + numAttempts + "times");
            }
        }
    } while (numAttempts <= this.maxRetries);

    return null;
}

}

IsTryAgain:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface IsTryAgain {
    int tryTimes() default 5;
}

Your service class method should add annotation @IsTryAgain and @Transactional

@IsTryAgain
@Transactional(rollbackFor = Exception.class)
public Product buyProduct(Product product) {
// your business logic 
}