Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC: What happens if I start a thread in a controller action?

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

like image 402
Erik Avatar asked Sep 17 '10 11:09

Erik


People also ask

Are Spring controllers thread-safe?

So YES, Spring MVC classes must be thread safe. You can do this by playing with different scopes for your class instance fields or just having local variables instead.

Does spring boot create a new thread for each request?

Absolutely NO since NIO!!! Spring Web runs in a web container Tomcat or Netty, it is tomcat or Netty's work to create thread, not spring mvc or spring webflux. If you use tomcat in a BIO model, it is definitely new thread per request.

Are Spring boots multithreaded?

Multithreading in spring boot is similar to multitasking, except that it allows numerous threads to run concurrently rather than processes.


2 Answers

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.

like image 166
Jaydeep Patel Avatar answered Oct 16 '22 12:10

Jaydeep Patel


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.

You are better off using a threadpool than creating new threads, so you don't risk resource exhaustion (threads stalling out are usually not independent events, if a thread hangs the next one probably will too, so you need a way to cut your losses). Methods annotated with @Async will be executed using an executor that you can configure as shown in the Spring documentation.

like image 22
Nathan Hughes Avatar answered Oct 16 '22 14:10

Nathan Hughes