views:

64

answers:

3

Hi,

in a Spring MVC Controller I would like to start a thread that continues work while my controller sends the response. Will this work with spring-mvc ?

Best Reagrds, Heinrich

+1  A: 

Yes, it'll work. On one web app I worked on, I needed to send a notification email depending on the user's action. I added a post-commit interceptor on the service, and had that fire off the email in a separate thread. (In my case that happened to be cleaner than putting the code in the controller, because I only wanted it to happen if the transaction committed.)

You do need to make sure the thread actually stops running at some point, either by setting daemon to true (if it's ok that stopping the server kills the thread without notice) or making sure the code in its run method will always terminate at some point.

BTW You are better off using a threadpool than creating new threads, so you don't risk resource exhaustion.

Nathan Hughes
Perhaps good to mention that the Controller cannot notify the user when sending an email failed (unless you use Callable.get() which kind of defeats the purpose of another thread here).
extraneon
If I want to use a thread pool, how can I achieve that there is only one threadpool used for all users/requests on the server? Edit: Can this be done by scoping the threadpool bean to "singleton" ?
Heinrich
A: 

Yes But if you are dependent on that thread to display response don't do that.
otherwise you can make use of Future.

org.life.java
A: 

Yes, You can start new Thread in Controller. But better way of doing asynchronous job is to use spring-scheduling support. You can leverage Quartz framework. That will manage your job.

This link will give you how to integrate this in your application.

Jaydeep