Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retry mechanism for optimistic locking (spring data + JPA)

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!

like image 469
Urbanleg Avatar asked Feb 10 '14 08:02

Urbanleg


People also ask

How can we avoid optimistic locking in JPA?

The OptimisticLockType. NONE disables the default optimistic locking mechanism for the TestEntity . However, that would only be useful if you inherited the @Version property from a base class which is annotated with @MappedSuperclass or @Inheritance .

How do I fix optimistic lock exception?

To resolve this error we have two ways: Get the latest object from the database and set the old object values if you need those values to be persisted to the new object and merge it. For the old object set the latest version from Database.

How do you implement optimistic locking in JPA?

In order to use optimistic locking, we need to have an entity including a property with @Version annotation. While using it, each transaction that reads data holds the value of the version property. Before the transaction wants to make an update, it checks the version property again.


2 Answers

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.

like image 109
MariuszS Avatar answered Nov 05 '22 18:11

MariuszS


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..!

like image 32
Ashish Jagtap Avatar answered Nov 05 '22 17:11

Ashish Jagtap