0

I have a spring mvc implementation with hibernate. We have quartz to take care of scheduled jobs. I have been reading up on threads and Spring's recommendation that all spawning of threads in Spring should be done through a managed bean (TaskExecutor?) i.e spawning of thread should be spring managed rather than developer just spawning a random thread calling new Thread(new Runnable{})

My question is: I have a product where users log in to my system, Every request from the browser is a thread, Tomcat takes care of servicing them etc. if asynchronous work is required we spawn threads while the request can return to the user. KISS, isn't it?

what am I missing with the lack of TaskExecutor implementation in my system? If we never thought of implementing it yet, how would having a spring managed TaskExecutor change the game for us? I am unable to find some article that clearly explains why I need my own implementation of TaskExecutor/dangers of spawning your own threads/performance gains/Design gains of letting Spring manage it etc.

Any resource shared or explanation will be appreciated. Grateful to people who will share their experience

veritas
  • 378
  • 1
  • 6
  • 16
  • Threads are quite heave to create, also each thread takes up memory and threads might live forever. Each thread takes **at least 1MB** (even when nothing happens) when created. If the number of threads created grows you will run out of resources (memory, cpu cores etc.). Also when in server environment (JEE) you should let the container (Tomcat, WebSphere whatever you use) own and handle the threads so it can efficiently manage them. Spring has `TaskExecutor` implementations for either fixed thread pools (ie create x threads and reuse) or to tap into the container managed thread pools. – M. Deinum Apr 28 '20 at 07:10
  • I would recommend you to read a bit on Thread vs ThreadPool, e.g. in https://stackoverflow.com/questions/230003/thread-vs-threadpool Also if you have lots of requests coming to your API, and on each request you spawn a new thread for asyncronicity then you can end up running into `java.lang.OutOfMemoryError: unable to create new native thread` , see https://dzone.com/articles/troubleshoot-outofmemoryerror-unable-to-create-new – Michael Kreutz Apr 28 '20 at 07:15
  • @MichaelKreutz Thanks for the resource. Why would I not run in outofmemoryerror even with a Spring managed TaskExecutor? – veritas Apr 28 '20 at 07:27
  • @M.Deinum Thanks for the explnation. Wanted to know a bit deeper about difference between pawning your own thread and not using TaskExecutor to tap into container (tomcat?) managed thread pools. – veritas Apr 28 '20 at 07:29
  • 1
    That is explained in the comment. A `TaskExecutor` generally has a pool of threads and doesn't create new ones on the fly, whereas you are creating threads when you need them. Eventually leeding to resource issues. – M. Deinum Apr 28 '20 at 07:30

0 Answers0