Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timing out the execution time of a controller/method in Spring

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.

like image 793
user980643 Avatar asked Oct 05 '11 15:10

user980643


1 Answers

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).

Further reading:

  • 25. Task Execution and Scheduling
  • How to use Servlet 3 @WebServlet & async with Spring MVC 3?
  • Support Servlet 3.0 (JSR-315)
like image 146
Tomasz Nurkiewicz Avatar answered Sep 19 '22 15:09

Tomasz Nurkiewicz