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:
- Client sends a request
- Servlet container allocates a thread and invokes a servlet in it
- The servlet calls request.startAsync(), saves the AsyncContext, and returns
- The container thread is exited all the way but the response remains open
- Some other thread uses the saved AsyncContext to complete the response
- 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.