I need to create a new thread from JSP. Is it a good idea to spawn a thread in JSP?
Is there any alternative approach?

- 17,914
- 8
- 63
- 82

- 131
- 1
- 5
- 13
2 Answers
It is absolutely not a good idea to manually spawn unmanaged threads in a JSP/Servlet web application. For sure not when done in the JSP side as it does not fit JSP's responsibilties in any way.
A thread is a relatively dangerous resource which needs to be treated with extreme care. Imagine that your JSP spawns a new thread on every request, then your web server would be killed after for example 1000 requests. You'd need to restart it.
Even when you control the thread usage and terminiation properly on a per-user basis, you still need to ensure that a single visitor cannot spawn more than one thread sessionwide. But still, when you have for example 1000 simultaneous sessions, your server would still be killed.
You want an application wide shared thread pool instead with a lock on maximum 10~20 threads or something. Normally, a bit decent Java EE container already provides it. You need to check its admin console and/or its manual as to how to configure and use it. You can eventually also create a thread pool yourself with help of for example ExecutorService
in a ServletContextListener
, but you should really understand very good how threading works and what implications can be if you are doing it wrong.
Here are several related questions to get some ideas from:
- Background timer task in JSP/Servlet web application
- How to run a background task in a servlet based web application?
- What is recommended way for spawning threads from a servlet in Tomcat
- Is it safe to start a new thread in a JSF managed bean?
- Spawning threads in a JSF managed bean for scheduled tasks using a timer
No, it's not. JSPs should not contain Java code. Use servlets for Java code, and then dispatch to the JSP to generate markup. Or use an MVC framework that will do that for you.
Whether it's a good idea to spawn a thread from the servlet depends on your specific use-case.