Search code examples
javaspring-mvcasynchronousconcurrencyrunnable

Spring MVC controller executes task asynchronously in Servlet 2.5


I am working on a Spring MVC application on Java 6 JVM running in a Servlet 2.5 (Tomcat) environment. I need to develop a controller method that will perform a long running task (large database query, generate report and deliver email to user). Justifiably, I want the task to run asynchronously. When I searched around, I found a lot of articles that were based on Servlet 3 and AsyncTask which I understand is not supported by my environment.

  • Can I use one of Java's executors (e.g. ExecutorService/NewFixedThreadPool) to execute a Runnable task from the controller method, so as to return from the method immediately while the task is progressing asynchronously?
  • How do I ensure that the executor is shutdown gracefully along with the web application?
  • Is there a Spring based executor I can use that somehow has access to all the auto-wired dependencies, rather than me creating final references to them?

Solution

  • Can I use one of Java's executors (e.g. ExecutorService/NewFixedThreadPool) to execute a Runnable task from the controller method

    Yes, you can. But since you're using Spring MVC, you could simply use its asynchronous method support.

    How do I ensure that the executor is shutdown gracefully along with the web application?

    You can register a ServletContextListener that shuts down the pool when the application is being destroyed. But if you use Spring's Async support, it will destroy theassociated executor automatically when the context is destroyed.

    Is there a Spring based executor I can use that somehow has access to all the auto-wired dependencies

    Async methods are Spring bean methods, and have access to the autowired dependencies of the bean they belong to.