Search This Blog

Saturday 21 July 2012

Are Interceptors Thread Safe ?

Our audit interceptor had several instance members that it used for audit management. For example there was the Set that kept track of all the new entities. What would happen of two threads simultaneously operate on the set. Or in a more general sense, is our interceptor thread safe ? Is it necessary for it to be thread safe ?
We have seen before that Interceptors are associated with a Session.
    final AuditInterceptor customInterceptor = new AuditInterceptor();
    Session session = sessionFactory.openSession(customInterceptor);
From the java doc for Hibernate Session
It is not intended that implementors be threadsafe. Instead each thread/transaction should obtain its own instance from a SessionFactory
Thus it is clear that we need to use our sessions in a non-shared manner. Or at any given time only a single thread should have access to the session. If we are to manually create new interceptors and assign them to our sessions, then we are assured our interceptors will be used by a single thread at any given time (assuming we are using our sessions in a single thread manner). Thus the above audit interceptor would work very fine in the above code.
The problem is that we do not always have control over the session creation code. For e.g. if we are using the sessionfactory.getCurrentSession(), the it is not possible to assign the interceptor as a constructor argument. Or if we are using Spring's Hibernate integration, then also the above approach fails. Hibernate provides an alternative approach for the above.
Configuring interceptors globally:
Configuration configuration = new Configuration();
    final AuditInterceptor customInterceptor = new AuditInterceptor();
    configuration = configuration.configure();
    configuration.setInterceptor(customInterceptor);        
    sessionFactory = configuration.buildSessionFactory();
In the above code we have added the interceptor to our Configuration object, before building the sessionFactory. The same interceptor is now available for all sessions. That means multiple threads are accessing the same interceptor object. Here it is imperative that the AuditInterceptor class is implemented in a thread safe manner.
What about Listeners ? Do they need to be thread safe.
Listeners whether they are configured from cfg file, or are created programmatically, they are always associated with the Configuration. This means they are known to the sessionFactory and used across sessions. In fact they can be thought as singletons in the Hibernate execution environment. As they are very definitely shared among sessions, Listeners need to be thread-safe.

No comments:

Post a Comment