How to recover after Hibernate’s OptimisticLockException

I’ve read many articles about optimistic locking and OptimisticLockException itself. Problem is that each one of them ended up getting their first exception and no word on recovery. What to do next? Repeat? If so, how? Or drop it? Is there any chance t…

I’ve read many articles about optimistic locking and OptimisticLockException itself. Problem is that each one of them ended up getting their first exception and no word on recovery. What to do next? Repeat? If so, how? Or drop it? Is there any chance to continue? How? Even more, documentation says that if you get Hibernate exception – you’re done, it’s not recoverable:

An exception thrown by Hibernate means you have to rollback your database transaction and close the Session immediately (this is discussed in more detail later in the chapter). If your Session is bound to the application, you have to stop the application. Rolling back the database transaction does not put your business objects back into the state they were at the start of the transaction. This means that the database state and the business objects will be out of sync. Usually this is not a problem, because exceptions are not recoverable and you will have to start over after rollback anyway.

Here is my attempt on this: repeatable and recoverable.

Business case

Let’s say we have distributed application with two web servers, connected to the same database. Applications use optimistic locking to avoid collisions. Customers buy lottery coupons, which are numbered from 1 to 100. In the same second Alice on web server 1 draws two coupons: 11 and 12. In the same moment Bob reserves two coupons on web server 2. It draws 11 and 13 for Bob and tries to write it back to database. But it fails, since Alice’s commit was first. I want a web application server to draw coupons for Bob again and then – try to save again until it succeeds.

Solution

For every request Hibernate associates different Session that is flushed at the end of request processing. If you hit OptimisticLockException then this Request Session is polluted and will be rolled back. To avoid this we will create a separate Hibernate’s Session especially for drawing coupons. If separate session fails – drop this session and try again in a new one. If it succeeds – merge it with a main request session. Request Session cannot be touched during draws. Take a look at the following picture:

On this picture yellow and green short-term sessions has failed with OptimisticLockException. Red session was successful and these objects are merged to a main session on the left.

Reservation entity

Key requirement here is to keep a domain you want to lock on as small as possible and not coupled directly to anything else. Best approach here is to create some Reservation entity with few fields, let’s say: couponId and customerId. For each Coupon create one Reservation row and use reserved boolean field as a reservation status. For coupon and customer use weak identifiers (long) instead of real entities. This way no object tree will be loaded and Reservation stays decoupled.

import  lombok.extern.slf4j.Slf4j;
import  org.hibernate.*;
import  org.hibernate.ejb.HibernateEntityManager;
import  org.springframework.orm.hibernate4.HibernateOptimisticLockingFailureException;

import  javax.persistence.OptimisticLockException;
import  javax.persistence.PersistenceContext;
import  java.util.List;

@Slf4j
public class  ReservationService  {

    @PersistenceContext
    private  HibernateEntityManager  hibernateEntityManager;

    @SuppressWarnings("uncheked")
    private  Iterable < Reservation >  reserveOptimistic(long  customerId,  final int  count)  throws  NoFreeReservationsException  {
        log.info("Trying to reserve {} reservations for customer {}",  count,  customerId);

        //This is the request session that needs to stay clean
        Session  currentSession =  hibernateEntityManager.getSession();
        Iterable < Reservation > reserved =  null;

        do  {
            //This is our temporary session to work on
            Session  newSession =  hibernateEntityManager.getSession().getSessionFactory().openSession();
            newSession.setFlushMode(FlushMode.COMMIT);
            Transaction  transaction = newSession.beginTransaction();

            List < Reservation > availableReservations =  null;

            try  {
                Query  query = newSession.createQuery("from Reservation r where r.reserved = false")
                    .setLockMode("optimistic",  LockMode.OPTIMISTIC)
                    .setMaxResults(count);

                availableReservations = query.list();

                //There is no available reservations to reserve
                if  (availableReservations.isEmpty()) {
                    throw new  NoFreeReservationsException();
                }

                for  (Reservation  available: availableReservations) {
                    available.reserve(customerId);
                    newSession.save(available);
                }

                //Commit can throw optimistic lock exception if it fails
                transaction.commit();

                //Commit succeeded - this reference is used outside try-catch-finally block
                reserved = availableReservations;

            } 
            catch  (OptimisticLockException  |  StaleObjectStateException  |  HibernateOptimisticLockingFailureException  e) {
                log.info("Optimistic lock exception occurred for customer {} and count {}: {} {}",  customerId,  count,  e.getClass(),  e.getMessage());

                transaction.rollback();

                for  (Reservation  availableMsisdn: availableReservations) {
                    newSession.evict(availableMsisdn);
                }
            } 
            finally  {
                newSession.close();
            }
            //Repeat until we reserve something
        }  while   (reserved ==  null);

        log.info("Successfully reserved {} reservations for customer {}",  count,  customerId);

        //Merge reserved entities to request session
        for  (Reservation  reservedMsisdn: reserved) {
            currentSession.merge(reservedMsisdn);
        }

        return  reserved;
    }
}

This code says it all. It tries to reserve some Reservations until it succeeds in a do-while loop. Main Request Session is not polluted and it achieves our goal.

I hope this example helps you in similar cases. It works as expected for a few months on our customer’s production site and I recommend this solution.

You May Also Like

Grails session timeout without XML

This article shows clean, non hacky way of configuring featureful event listeners for Grails application servlet context. Feat. HttpSessionListener as a Spring bean example with session timeout depending on whether user account is premium or not.

Common approaches

Speaking of session timeout config in Grails, a default approach is to install templates with a command. This way we got direct access to web.xml file. Also more unnecessary files are created. Despite that unnecessary files are unnecessary, we should also remember some other common knowledge: XML is not for humans.

Another, a bit more hacky, way is to create mysterious scripts/_Events.groovy file. Inside of which, by using not less enigmatic closure: eventWebXmlEnd = { filename -> ... }we can parse and hack into web.xml with a help of XmlSlurper.
Even though lot of Grails plugins do it similar way, still it’s not really straightforward, is it? Besides, where’s the IDE support? Hello!?

Examples of both above ways can be seen on StackOverflow.

Simpler and cleaner way

By adding just a single line to the already generated init closure we have it done:
class BootStrap {

def init = { servletContext ->
servletContext.addListener(OurListenerClass)
}
}

Allrighty, this is enough to avoid XML. Sweets are served after the main course though :)

Listener as a Spring bean

Let us assume we have a requirement. Set a longer session timeout for premium user account.
Users are authenticated upon session creation through SSO.

To easy meet the requirements just instantiate the CustomTimeoutSessionListener as Spring bean at resources.groovy. We also going to need some source of the user custom session timeout. Let say a ConfigService.
beans = {    
customTimeoutSessionListener(CustomTimeoutSessionListener) {
configService = ref('configService')
}
}

With such approach BootStrap.groovy has to by slightly modified. To keep control on listener instantation, instead of passing listener class type, Spring bean is injected by Grails and the instance passed:
class BootStrap {

def customTimeoutSessionListener

def init = { servletContext ->
servletContext.addListener(customTimeoutSessionListener)
}
}

An example CustomTimeoutSessionListener implementation can look like:
import javax.servlet.http.HttpSessionEvent    
import javax.servlet.http.HttpSessionListener
import your.app.ConfigService

class CustomTimeoutSessionListener implements HttpSessionListener {

ConfigService configService

@Override
void sessionCreated(HttpSessionEvent httpSessionEvent) {
httpSessionEvent.session.maxInactiveInterval = configService.sessionTimeoutSeconds
}

@Override
void sessionDestroyed(HttpSessionEvent httpSessionEvent) { /* nothing to implement */ }
}
Having at hand all power of the Spring IoC this is surely a good place to load some persisted user’s account stuff into the session or to notify any other adequate bean about user presence.

Wait, what about the user context?

Honest answer is: that depends on your case. Yet here’s an example of getSessionTimeoutMinutes() implementation using Spring Security:
import org.springframework.security.core.context.SecurityContextHolder    

class ConfigService {

static final int 3H = 3 * 60 * 60
static final int QUARTER = 15 * 60

int getSessionTimeoutSeconds() {

String username = SecurityContextHolder.context?.authentication?.principal
def account = Account.findByUsername(username)

return account?.premium ? 3H : QUARTER
}
}
This example is simplified. Does not contain much of defensive programming. Just an assumption that principal is already set and is a String - unique username. Thanks to Grails convention our ConfigService is transactional so the Account domain class can use GORM dynamic finder.
OK, config fetching implementation details are out of scope here anyway. You can get, load, fetch, obtain from wherever you like to. Domain persistence, principal object, role config, external file and so on...

Any gotchas?

There is one. When running grails test command, servletContext comes as some mocked class instance without addListener method. Thus we going to have a MissingMethodException when running tests :(

Solution is typical:
def init = { servletContext ->
if (Environment.current != Environment.TEST) {
servletContext.addListener(customTimeoutSessionListener)
}
}
An unnecessary obstacle if you ask me. Should I submit a Jira issue about that?

TL;DR

Just implement a HttpSessionListener. Create a Spring bean of the listener. Inject it into BootStrap.groovy and call servletContext.addListener(injectedListener).