Home:ALL Converter>Async thread completes before Servlet returns in Spring MVC 3

Async thread completes before Servlet returns in Spring MVC 3

Ask Time:2015-04-17T20:14:22         Author:vladone

Json Formatter

I am trying to implement an Async Controller as in the following example:

public Callable<Campaign> findCampaignById(@PathVariable Long id) {
    return new Callable<Campaign>() {
        @Override
        public Campaign call() throws Exception {           
            Campaign campaign = loadCampaign();
            //Thread.sleep(2000);
            return campaign;
        }
    };                  
}

This tutorial https://spring.io/blog/2012/05/07/spring-mvc-3-2-preview-introducing-servlet-3-async-support explains what happens behind the scene:

  1. Client sends a request
  2. Servlet container allocates a thread and invokes a servlet in it
  3. The servlet calls request.startAsync(), saves the AsyncContext, and returns
  4. The container thread is exited all the way but the response remains open
  5. Some other thread uses the saved AsyncContext to complete the response
  6. Client receives the response

Issue: There are situations when Callable thread may complete before servlet returns. In this situation I get 404 Page not found exception.
It looks like if the Callable is already executed then the AsyncContext is empty (see step 3) so there is nothing to be execute and nothing to be returned during step 5, respectively 6.

Question: Am I doing something wrong? How can be sure that Callable is always executed after Servlet returns?
Note that If I call Thread.sleep(2000); I never get 404 exception.

Author:vladone,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/29698929/async-thread-completes-before-servlet-returns-in-spring-mvc-3
yy