Search code examples
javaspringthreadpoolthreadpoolexecutor

Running a Spring project without a Spring TaskExecutor or thread pool implementation


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


Solution

  • Threads are quite heave to create. 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.).

    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.

    NOTE: with newer versions of Spring 6.1 there is even out-of-the-box support for virtual threads.