I have a Spring controller that is currently being accessed normally, but i want to change the implementation in such a way that if the task the controller is performing takes more than a defined time for instance 10 seconds then the controller can respond with a "your request is being processed message" to the caller, but if the method returns within time then the response is passed to the calling method from the controller, in other words i want timed asynchronous execution from a Spring controller.
NB: This is not exactly TaskExecutor domain(at least according to my understanding) because i don't want to just hand over execution to the TaskExecutor and return immediately.
I use Spring 3.0 and Java 1.5 and the controllers don't have views, i just want to write the output direct to stream, which the calling client expects.
Well, it is the TaskExecutor
domain. In your controller simply wrap your processing logic in Callable
, submit it to the AsyncTaskExecutor
and wait up to 10 seconds. That's it!
final Future<ModelAndView> future = asyncTaskExecutor.submit(new Callable<ModelAndView>() {
@Override
public ModelAndView call() throws Exception {
//lengthy computations...
return new ModelAndView("done");
}
});
try {
return future.get(10, TimeUnit.SECONDS);
} catch (TimeoutException e) {
return new ModelAndView("timeout");
}
Of course this is a bit nasty, especially when it occurs more than once in one controller. If this is the case, you should have a look at servlet 3.0 asynchronous support (see below).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With