title: @Async not working in Spring API rest with Interfaces
body: <p>I'm working with @Async to stored some data in parallel in the database with hibernate. I need to do that because before saving the information to the database I need to run some task that takes several minutes. So I implemented @Async.</p>
  
  <p>The issue is that @Async seems to not be working. Please find the code below:</p>
  
  <p>WebConfig</p>
  
  <pre><code>@Configuration
  @EnableAsync
  @EnableWebMvc
  public class WebConfig extends WebMvcConfigurerAdapter {
  
  }
  </code></pre>
  
  <p>StudentServiceImpl:</p>
  
  <pre><code>@Autowired
  RunSomeTaskService runSomeTaskService;
  
  @Override
  Transactional
  public Response saveWithoutWaiting(StudentBO[] students, String username) throws Exception {
  ...
  for (StudentBO student : students) {
      ....
      Future&lt;Response&gt; response = runSomeTaskService.doTasks(student);
      //Finish without waiting for doTasks().
  }
  
  @Override
      Transactional
      public Response saveWithWaiting(StudentBO[] students, String username) throws Exception {
      ...
      for (StudentBO student : students) {
          ....
          Future&lt;Response&gt; response = runSomeTaskService.doTasks(student);
          //Finish and wait for doTasks().
          response.get();
      }
  </code></pre>
  
  <p>RunSomeTaskService:</p>
  
  <pre><code>public interface RunSomeTaskService{
      @Async
      public Future&lt;Response&gt; doTasks(Student student);
  }
  </code></pre>
  
  <p>RunSomeTaskServiceImpl:</p>
  
  <pre><code>public class RunSomeTaskServiceImpl extends CommonService implements RunSomeTaskService{
  
  Student student;
  @Override
      public Future&lt;Response&gt; doTasks(Student student) {
            Response response = new Response();
            this.student = student;
            //do Task
            return new AsyncResult&lt;Response&gt;(response);
         }
  }
  </code></pre>
  
  <p>web.xml</p>
  
  <pre><code>&lt;web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
            http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0"&gt;
  
      &lt;display-name&gt;Sample Spring Maven Project&lt;/display-name&gt;
  
      &lt;servlet&gt;
          &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt;
          &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
          &lt;init-param&gt;
              &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
              &lt;param-value&gt;/WEB-INF/spring-config.xml&lt;/param-value&gt;
          &lt;/init-param&gt;
          &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
          &lt;async-supported&gt;true&lt;/async-supported&gt;
      &lt;/servlet&gt;
  
      &lt;servlet-mapping&gt;
          &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt;
          &lt;url-pattern&gt;/&lt;/url-pattern&gt;
      &lt;/servlet-mapping&gt;
  
  &lt;filter&gt;
      &lt;filter-name&gt;encodingFilter&lt;/filter-name&gt;
      &lt;filter-class&gt;
              org.springframework.web.filter.CharacterEncodingFilter
          &lt;/filter-class&gt;
      &lt;init-param&gt;
        &lt;param-name&gt;encoding&lt;/param-name&gt;
        &lt;param-value&gt;UTF-8&lt;/param-value&gt;
      &lt;/init-param&gt;
    &lt;/filter&gt;
    &lt;filter-mapping&gt;
      &lt;filter-name&gt;encodingFilter&lt;/filter-name&gt;
      &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
    &lt;/filter-mapping&gt;
    &lt;filter&gt;
      &lt;filter-name&gt;jwtTokenAuthFilter&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;jwtTokenAuthFilter&lt;/filter-name&gt;
      &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
    &lt;/filter-mapping&gt;
  &lt;/web-app&gt;
  </code></pre>
  
  <p>spring.config.xml</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &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:util="http://www.springframework.org/schema/util" 
      xmlns:mvc="http://www.springframework.org/schema/mvc"
      xmlns:tx="http://www.springframework.org/schema/tx"
      xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-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"&gt;
  
      &lt;context:annotation-config  /&gt;
      &lt;context:component-scan base-package="com.app.controller" /&gt;
      &lt;tx:annotation-driven transaction-manager="transactionManager"/&gt;
      &lt;mvc:annotation-driven /&gt;
  
      &lt;bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
          ...
      &lt;/bean&gt;
  
      &lt;bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"&gt;
  ...
      &lt;/bean&gt;
  
  
      &lt;bean id="sessionFactory"
          class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"&gt;
          &lt;property name="dataSource" ref="dataSource" /&gt;
          &lt;property name="annotatedClasses"&gt;
              &lt;list&gt;
                  &lt;value&gt;//every model generated with Hibernate&lt;/value&gt;
              &lt;/list&gt;
          &lt;/property&gt;
          &lt;property name="hibernateProperties"&gt;
              &lt;props&gt;
                  &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQL5Dialect&lt;/prop&gt;
                  &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt;
              &lt;/props&gt;
          &lt;/property&gt;
      &lt;/bean&gt;
  
      &lt;bean id="transactionManager"
          class="org.springframework.orm.hibernate5.HibernateTransactionManager"&gt;
          &lt;property name="sessionFactory" ref="sessionFactory" /&gt;
      &lt;/bean&gt;
  
      &lt;bean id="persistenceExceptionTranslationPostProcessor"
          class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /&gt;
  
      &lt;bean id="studentService" class="com.app.services.StudentServiceImpl"&gt;&lt;/bean&gt;
      &lt;bean id="studentDao" class="com.app.dao.StudentDaoImpl"&gt;&lt;/bean&gt;
      ...
  
      &lt;bean id="jwtTokenAuthFilter" class="com.app.security.JWTTokenAuthFilter" /&gt;       
  &lt;/beans&gt;
  </code></pre>
  
  <p>So, could you please help me to understand why @Async is not working?</p>
  
  <p>UPDATE: @Async is now working, but I'm not getting the expected results.</p>
  
  <p>For the case, that I have to wait for the result (sync case)  CompletableFuture.get() is not waiting for the response and I'm getting and error:</p>
  
  <p>My code:</p>
  
  <pre><code>CompletableFuture&lt;Response&gt; res = extractDataService.doTask(student);
  </code></pre>
  
  <p>The error:</p>
  
  <pre><code>org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions. Collection : &lt;unknown&gt;
  Collection contents: [[]]
          at org.hibernate.collection.internal.AbstractPersistentCollection.setCurrentSession(AbstractPersistentCollection.java:627)
          at org.hibernate.event.internal.OnUpdateVisitor.processCollection(OnUpdateVisitor.java:46)
          at org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:104)
          at org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:65)
          at org.hibernate.event.internal.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:59)
          at org.hibernate.event.internal.AbstractVisitor.process(AbstractVisitor.java:126)
          at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:293)
          at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:227)
          at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:92)
          at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
          at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:648)
          at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:640)
          at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:635)
          at com.app.dao.CommonDaoImpl.addOrUpdate(CommonDaoImpl.java:28)
          at com.app.services.ExtractDataServiceImpl.doExtraction(ExtractDataServiceImpl.java:361)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
          at java.lang.reflect.Method.invoke(Method.java:498)
          at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
          at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
          at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
          at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
          at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
          at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
          at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
          at org.springframework.aop.interceptor.AsyncExecutionInterceptor$1.call(AsyncExecutionInterceptor.java:108)
          at org.springframework.aop.interceptor.AsyncExecutionAspectSupport$CompletableFutureDelegate$1.get(AsyncExecutionAspectSupport.java:237)
          at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590)
          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
          at java.lang.Thread.run(Thread.java:748)
  </code></pre>
  
  <p>When I don't have to wait and I execute several cases in Async way I get:</p>
  
  <pre><code>12:17:44.040 [DEMO-4] DEBUG o.h.r.t.b.j.i.JdbcResourceLocalTransactionCoordinatorImpl - JDBC transaction marked for rollback-only (exception provided for stack trace)
  java.lang.Exception: exception just for purpose of providing stack trace
          at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.markRollbackOnly(JdbcResourceLocalTransactionCoordinatorImpl.java:265) [hibernate-core-5.0.6.Final.jar:5.0.6.Final]
          at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:156) [hibernate-core-5.0.6.Final.jar:5.0.6.Final]
          at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38) [hibernate-core-5.0.6.Final.jar:5.0.6.Final]
          at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231) [hibernate-core-5.0.6.Final.jar:5.0.6.Final]
          at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65) [hibernate-core-5.0.6.Final.jar:5.0.6.Final]
          at org.springframework.orm.hibernate5.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:581) [spring-orm-4.2.4.RELEASE.jar:4.2.4.RELEASE]
          at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761) [spring-tx-4.2.4.RELEASE.jar:4.2.4.RELEASE]
          at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730) [spring-tx-4.2.4.RELEASE.jar:4.2.4.RELEASE]
          at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:485) [spring-tx-4.2.4.RELEASE.jar:4.2.4.RELEASE]
          at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291) [spring-tx-4.2.4.RELEASE.jar:4.2.4.RELEASE]
          at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) [spring-tx-4.2.4.RELEASE.jar:4.2.4.RELEASE]
          at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
          at org.springframework.aop.interceptor.AsyncExecutionInterceptor$1.call(AsyncExecutionInterceptor.java:108) [spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
          at org.springframework.aop.interceptor.AsyncExecutionAspectSupport$CompletableFutureDelegate$1.get(AsyncExecutionAspectSupport.java:237) [spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
          at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590) [na:1.8.0_171]
          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_171]
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_171]
          at java.lang.Thread.run(Thread.java:748) [na:1.8.0_171]
  12:17:44.043 [DEMO-4] DEBUG o.s.o.h.HibernateTransactionManager - Initiating transaction rollback after commit exception
  org.hibernate.AssertionFailure: null id in com.app.model.FieldValue entry (don't flush the Session after an exception occurs)
  </code></pre>