title: org.hibernate.AssertionFailure: possible non-threadsafe access to the session
body: <p>I am developing a web application with AngularJs as front-end and Spring+Hibernate as the service layer. Service Layer has a set of REST API's that are consumed by AngularJs. The front end of the application has no major issues. But in the service layer, I am facing some concurrency issues. For some scenarios, I have to make parallel Asychronous calls to same REST API's from the same http session. When I do that, there are times when I get the above error. Actually, the error keeps of changing everytime. Sometimes I also get NULLPointerException on Query.List() operation. Sometimes I get TransactionResourceAlreadyClosed exception. Various configurations and code snippets are attached below.</p>
  
  <p>Web.xml</p>
  
  <pre><code>&lt;context-param&gt;
      &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
      &lt;param-value&gt;WEB-INF/config/fs-cxf-serverContext.xml,WEB-INF/config/fs-spring-jpa-config.xml,WEB-INF/config/security-beans.xml&lt;/param-value&gt;
  &lt;/context-param&gt;
  
  &lt;listener&gt;
      &lt;listener-class&gt;org.springframework.web.context.request.RequestContextListener&lt;/listener-class&gt;
  &lt;/listener&gt;
  &lt;listener&gt;
      &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
  &lt;/listener&gt;
  
  &lt;filter&gt;
      &lt;filter-name&gt;CorsFilter&lt;/filter-name&gt;
      &lt;filter-class&gt;org.apache.catalina.filters.CorsFilter&lt;/filter-class&gt;
      &lt;init-param&gt;
          &lt;param-name&gt;cors.allowed.origins&lt;/param-name&gt;
          &lt;param-value&gt;*&lt;/param-value&gt;
      &lt;/init-param&gt;
      &lt;init-param&gt;
          &lt;param-name&gt;cors.allowed.headers&lt;/param-name&gt;
          &lt;param-value&gt;Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Access-Control-Allow-Origin&lt;/param-value&gt;
      &lt;/init-param&gt;
      &lt;init-param&gt;
          &lt;param-name&gt;cors.exposed.headers&lt;/param-name&gt;
          &lt;param-value&gt;Access-Control-Allow-Origin&lt;/param-value&gt;
      &lt;/init-param&gt;
      &lt;init-param&gt;
          &lt;param-name&gt;cors.allowed.methods&lt;/param-name&gt;
          &lt;param-value&gt;GET, POST, PUT, DELETE, OPTIONS, HEAD&lt;/param-value&gt;
      &lt;/init-param&gt;
  &lt;/filter&gt;
  &lt;filter-mapping&gt;
      &lt;filter-name&gt;CorsFilter&lt;/filter-name&gt;
      &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;
  
  &lt;filter&gt;
      &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
      &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt;
  &lt;/filter&gt;
  &lt;filter-mapping&gt;
      &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
      &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;
  
  &lt;servlet&gt;
      &lt;description&gt;Servlet to Initialize and shutdown the Scheduler&lt;/description&gt;
      &lt;servlet-name&gt;QuartzInitializer&lt;/servlet-name&gt;
      &lt;servlet-class&gt;org.quartz.ee.servlet.QuartzInitializerServlet&lt;/servlet-class&gt;
      &lt;init-param&gt;
          &lt;param-name&gt;config-file&lt;/param-name&gt;
          &lt;param-value&gt;quartz.properties&lt;/param-value&gt;
      &lt;/init-param&gt;
      &lt;init-param&gt;
          &lt;param-name&gt;shutdown-on-unload&lt;/param-name&gt;
          &lt;param-value&gt;true&lt;/param-value&gt;
      &lt;/init-param&gt;
      &lt;init-param&gt;
          &lt;param-name&gt;start-scheduler-on-load&lt;/param-name&gt;
          &lt;param-value&gt;true&lt;/param-value&gt;
      &lt;/init-param&gt;
      &lt;load-on-startup&gt;2&lt;/load-on-startup&gt;
  &lt;/servlet&gt;
  &lt;servlet&gt;
      &lt;servlet-name&gt;CXFServlet&lt;/servlet-name&gt;
      &lt;servlet-class&gt;org.apache.cxf.transport.servlet.CXFServlet&lt;/servlet-class&gt;
      &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
  &lt;/servlet&gt;
  
  &lt;servlet-mapping&gt;
      &lt;servlet-name&gt;CXFServlet&lt;/servlet-name&gt;
      &lt;url-pattern&gt;/services/*&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
  
  &lt;resource-ref&gt;
      &lt;res-ref-name&gt;jdbc/foodsafetyDS&lt;/res-ref-name&gt;
      &lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt;
      &lt;res-auth&gt;Container&lt;/res-auth&gt;
      &lt;res-sharing-scope&gt;Shareable&lt;/res-sharing-scope&gt;
  &lt;/resource-ref&gt;
  </code></pre>
  
  <p></p>
  
  <p>JPA Configuration</p>
  
  <pre><code>&lt;beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:task="http://www.springframework.org/schema/task"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
      http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd"&gt;
  
  &lt;!-- Hibernate session factory --&gt;
  &lt;bean id="sessionFactory"
      class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt;
      &lt;property name="configLocation" value="classpath:hibernate.cfg.xml" /&gt;
      &lt;property name="entityInterceptor"&gt;
          &lt;bean class="com.cts.foodSafety.interceptor.AuditLogInterceptor"/&gt;
      &lt;/property&gt;
  &lt;/bean&gt;
  
  &lt;bean id="transactionManager"
      class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt;
      &lt;property name="sessionFactory" ref="sessionFactory" /&gt;
  &lt;/bean&gt;
  
  &lt;bean id="persistenceAnnotation"
      class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /&gt;
  
  &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt;
  &lt;task:annotation-driven/&gt;
  </code></pre>
  
  <p></p>
  
  <p>Hibernate.cfg.xml</p>
  
  <pre><code>&lt;hibernate-configuration&gt;
  &lt;session-factory&gt;
      &lt;property name="hibernate.connection.driver_class"&gt;com.mysql.jdbc.Driver&lt;/property&gt;
      &lt;property name="hibernate.dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;
      &lt;property name="hibernate.connection.datasource"&gt;java:comp/env/jdbc/foodsafetyDS&lt;/property&gt;
      &lt;property name="hbm2ddl.auto"&gt;update&lt;/property&gt;
      &lt;property name="show_sql"&gt;false&lt;/property&gt;
  
      &lt;!-- Mapping with model class containing annotations --&gt;
  </code></pre>
  
  <p>I have created a simple rest controller using CXF. REST end point is as below</p>
  
  <pre><code>@Path("/units")
  @Produces(MediaType.APPLICATION_JSON)
  public interface UnitService extends Serializable {
  
  @GET
  @Path("/getGraphData/{type}")
  @Produces(MediaType.APPLICATION_JSON)
  public UnitServiceBean getGraphData(@PathParam("type") String type)
          throws FoodSafetyException;
  </code></pre>
  
  <p>}</p>
  
  <p>Implementation of the controller is as below</p>
  
  <p>xxxServiceImpl.java</p>
  
  <pre><code>@Service("unit")
  @Transactional
  public class xxxServiceImpl implements xxxService {
  
  private static final long serialVersionUID = 1L;
  
  @Autowired
  xxxDelegate xxxDelegate;
  
  @Override
  public UnitServiceBean getGraphData(String type) throws FoodSafetyException {
      UnitServiceBean bean = new UnitServiceBean();
  
      List&lt;String[]&gt; data = unitDelegate.getGraphData(type);
      ....
      ....
      return bean;
  }
  </code></pre>
  
  <p>Delegate calls the DAO. (We haven't introduced the Business object as of now). Implementation of DAO is as below</p>
  
  <pre><code>@Component
  public class UnitDAOImpl extends FoodSafetyDAO implements UnitDAO {
  @Override
  public List&lt;String[]&gt; getGraphData(String type) {
      List&lt;String[]&gt; data = new ArrayList&lt;String[]&gt;();
      Map&lt;String, List&lt;UnitReadingEntity&gt;&gt; readings = new HashMap&lt;String, List&lt;UnitReadingEntity&gt;&gt;();
  
      SimpleDateFormat df = CommonConstants.TIME_FORMATTER;
  
      // Get all the Units
      Query query = getSession().getNamedQuery(
              QueryConstants.FIND_UNITS_BY_TYPE);
      query.setParameter(QueryConstants.TYPE, type);
      List&lt;UnitEntity&gt; units = (List&lt;UnitEntity&gt;) query.list();
      if (units != null &amp;&amp; units.size() != 0) {
          .....
          .....
  
          for (UnitEntity unit : units) {
              Calendar cal1 = Calendar.getInstance();
              cal1.add(Calendar.DAY_OF_YEAR, -1);
              query = getSession().getNamedQuery(
                      QueryConstants.FIND_READING_BY_UNIT_TIME).setLong(
                      QueryConstants.UNIT_ID, unit.getUnitId());
  
              List&lt;UnitReadingEntity&gt; rr = query.list();
              ...
              ...
          }
      }
  
      return data;
  }
  </code></pre>
  
  <p>Now, when I call the REST service "getGraphData" once using POSTMAN etc. it works fine without any issue. But when I simulate concurrent call to this rest service using I get following error</p>
  
  <pre><code>Caused by: org.hibernate.AssertionFailure: possible non-threadsafe access to the session
  at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:130)
  at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1108)
  at org.hibernate.loader.Loader.processResultSet(Loader.java:964)
  at org.hibernate.loader.Loader.doQuery(Loader.java:911)
  at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342)
  at org.hibernate.loader.Loader.doList(Loader.java:2526)
  at org.hibernate.loader.Loader.doList(Loader.java:2512)
  at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2342)
  at org.hibernate.loader.Loader.list(Loader.java:2337)
  at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:495)
  at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:356)
  at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
  at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1269)
  at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
  at com.cts.foodSafety.model.dao.impl.UnitDAOImpl.getGraphData(UnitDAOImpl.java:255)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
  at java.lang.reflect.Method.invoke(Method.java:597)
  at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
  at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:51)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
  at org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:42)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
  at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
  at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
  at com.sun.proxy.$Proxy51.getGraphData(Unknown Source)
  at com.cts.foodSafety.delegate.UnitDelegate.getGraphData(UnitDelegate.java:39)
  at com.cts.foodSafety.delegate.UnitDelegate$$FastClassByCGLIB$$aac35d0d.invoke(&lt;generated&gt;)
  at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
  at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
  at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:51)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
  at org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:42)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
  at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
  at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
  at com.cts.foodSafety.delegate.UnitDelegate$$EnhancerByCGLIB$$75af66.getGraphData(&lt;generated&gt;)
  at com.cts.foodSafety.service.impl.UnitServiceImpl.getGraphData(UnitServiceImpl.java:108)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
  at java.lang.reflect.Method.invoke(Method.java:597)
  at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
  at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:51)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
  at org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:42)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
  at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:55)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
  at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
  at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
  at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
  at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
  at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
  at com.sun.proxy.$Proxy72.getGraphData(Unknown Source)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
  at java.lang.reflect.Method.invoke(Method.java:597)
  at org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:180)
  at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
  </code></pre>
  
  <p>Client that I used to make concurrent request is as below</p>
  
  <pre><code>public class RestClient implements Runnable{
  
  private String i;
  
  public RestClient(String x) {
      i=x;
  }
  public static void main(String[] args) {
  
      for(int i =1;i&lt;=2;i++) {
          Thread t = new Thread(new RestClient(String.valueOf(i)));
          t.start();
      }
  }
  
  @Override
  public void run() {
      System.out.println("started " + i);
        try {
  
              URL url = new URL(" http://localhost:8080/fs/services/units/getGraphData/Freezer");
              HttpURLConnection conn = (HttpURLConnection) url.openConnection();
              conn.setRequestMethod("GET");
              conn.setRequestProperty("Accept", "application/json");
  
              if (conn.getResponseCode() != 204) {
                  throw new RuntimeException("Failed : HTTP error code : "
                          + conn.getResponseCode());
              }
  </code></pre>
  
  <p>Any pointers/suggestions ? I have gone through a lot of material on sessions and transaction management in Spring+hibernate. But I am not able to get my head around this problem.</p>