How to retry JPA transactions after an OptimisticLockException

Imagine having a tool that can automatically detect if you are using JPA and Hibernate properly. Hypersistence Optimizer is that tool!

Introduction

This is the third part of the optimistic locking series, and I will discuss how we can implement the automatic retry mechanism when dealing with JPA repositories.

You can find the introductory part here and the MongoDB implementation here.

Retry

JPA requires running the Persistence Context code inside a transaction, and if our Transaction Manager catches a RuntimeException, it initiates the rollback process. This makes the Persistence Context unusable since we should discard it along with the rolled-back Transaction.

Therefore it’s safer to retry the business logic operation when we are not within a running transaction.

For this, we altered our @Retry annotation like this:

public @interface Retry {

    Class<? extends Exception>[] on();

    int times() default 1;

    boolean failInTransaction() default true;
}

We here added the failInTransaction property which is set to true by default.

The Aspect was also changed to take into consideration the new annotation property.

private Object proceed(
        ProceedingJoinPoint pjp, 
        Retry retryAnnotation) 
    throws Throwable {
    
    int times = retryAnnotation.times();
    
    Class<? extends Throwable>[] retryOn = retryAnnotation.on();
    
    Assert.isTrue(times > 0, "@Retry{times} should be greater than 0!");
    Assert.isTrue(retryOn.length > 0, "@Retry{on} should have at least one Throwable!");
    
    if (retryAnnotation.failInTransaction() && 
        TransactionSynchronizationManager.isActualTransactionActive()) {
        
        throw new IllegalTransactionStateException(
                "You shouldn't retry an operation from withing an existing Transaction." +
                "This is because we can't retry if the current Transaction was already rollbacked!");
    }
    
    LOGGER.info(
        "Proceed with {} retries on {}", 
        times, 
        Arrays.toString(retryOn)
    );
    
    return tryProceeding(pjp, times, retryOn);
}

If we are running inside a Transaction and we don’t suppress the default safe-check we then throw an IllegalTransactionStateException, notifying the caller that’s safer to retry if the Transaction is contained in the proceeding service call, without nesting our intercepting aspect.

This utility is part of my db-util project along with the MongoDB optimistic concurrency control retry mechanism.

Since it’s already available in Maven Central Repository, you can easily use it by just adding this dependency to your pom.xml:

<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>db-util</artifactId>
    <version>0.0.1</version>
</dependency>

You can configure the optimistic retry as simple as this:

@Retry(times = 10, on = OptimisticLockException.class)
public Product updateName(
        final Long id, 
        final String name) {
    return transactionTemplate.execute(
        new TransactionCallback<Product>() {
            @Override
            public Product doInTransaction(
                    TransactionStatus status) {
                Product product = entityManager.find(Product.class, id);
                product.setName(name);
               
                LOGGER.info("Updating product {} name to {}", product, name);		
                return product;
            }
        }
    );
}

Running a JUnit test which schedules 10 threads to update the same entity will generate optimistic locking exceptions and this what the test outputs.

Line 102: INFO  [Thread-3]: v.c.a.OptimisticConcurrencyControlAspect - Optimistic locking detected, 9 remaining retries on [class javax.persistence.OptimisticLockException]
Line 103: INFO  [Thread-12]: v.c.a.OptimisticConcurrencyControlAspect - Optimistic locking detected, 9 remaining retries on [class javax.persistence.OptimisticLockException]
Line 104: INFO  [Thread-9]: v.c.a.OptimisticConcurrencyControlAspect - Optimistic locking detected, 9 remaining retries on [class javax.persistence.OptimisticLockException]
Line 105: INFO  [Thread-6]: v.c.a.OptimisticConcurrencyControlAspect - Optimistic locking detected, 9 remaining retries on [class javax.persistence.OptimisticLockException]
Line 109: INFO  [Thread-9]: v.c.a.OptimisticConcurrencyControlAspect - Optimistic locking detected, 8 remaining retries on [class javax.persistence.OptimisticLockException]
Line 110: INFO  [Thread-7]: v.c.a.OptimisticConcurrencyControlAspect - Optimistic locking detected, 9 remaining retries on [class javax.persistence.OptimisticLockException]
Line 114: INFO  [Thread-3]: v.c.a.OptimisticConcurrencyControlAspect - Optimistic locking detected, 8 remaining retries on [class javax.persistence.OptimisticLockException]
Line 115: INFO  [Thread-5]: v.c.a.OptimisticConcurrencyControlAspect - Optimistic locking detected, 9 remaining retries on [class javax.persistence.OptimisticLockException]
Line 117: INFO  [Thread-11]: v.c.a.OptimisticConcurrencyControlAspect - Optimistic locking detected, 9 remaining retries on [class javax.persistence.OptimisticLockException]
Line 118: INFO  [Thread-6]: v.c.a.OptimisticConcurrencyControlAspect - Optimistic locking detected, 8 remaining retries on [class javax.persistence.OptimisticLockException]
Line 123: INFO  [Thread-7]: v.c.a.OptimisticConcurrencyControlAspect - Optimistic locking detected, 8 remaining retries on [class javax.persistence.OptimisticLockException]
Line 124: INFO  [Thread-5]: v.c.a.OptimisticConcurrencyControlAspect - Optimistic locking detected, 8 remaining retries on [class javax.persistence.OptimisticLockException]
Line 126: INFO  [Thread-11]: v.c.a.OptimisticConcurrencyControlAspect - Optimistic locking detected, 8 remaining retries on [class javax.persistence.OptimisticLockException]
Line 129: INFO  [Thread-5]: v.c.a.OptimisticConcurrencyControlAspect - Optimistic locking detected, 7 remaining retries on [class javax.persistence.OptimisticLockException]

If you enjoyed this article, I bet you are going to love my Book and Video Courses as well.

Seize the deal! 50% discount. Seize the deal! 50% discount.

Conclusion

So we reused the same optimistic locking retry logic we first implemented for our MongoDB batch processors, therefore proving we can easily implement such behavior even for JPA repositories.

Code available on GitHub.

FREE EBOOK

2 Comments on “How to retry JPA transactions after an OptimisticLockException

  1. This approach doesn’t make sense in most cases, since the conflict that is the cause of the OptimisticLockException cannot be handled simply by retrying. What you’re effectively doing is to override the previous modification. And to prevent accidental overriding optimistic locking was created!

    • That’s true. This approach does not make sense in many cases. However, it’s useful if you have a highly concurrent environment where a batch process tries to update certain attributes that are not meant to trigger optimistic locking failures. Imagine having a Product for which a batch process updates an estimated quantity number. That should not trigger an optimistic locking for a concurrent transaction modifying the price since the “estimated price” is just a flag that tells buyers that this product is soon to be taken out from the store catalog.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.