Retry mechanism for optimistic locking (spring data + JPA)

Urbanleg picture Urbanleg · Feb 10, 2014 · Viewed 12.2k times · Source

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!

Answer

MariuszS picture MariuszS · Aug 7, 2017

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.