我可以在JSP中生成新线程吗? [英] Can I spawn new Threads in JSP?

查看:212
本文介绍了我可以在JSP中生成新线程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从JSP创建一个新线程.在JSP中生成线程是个好主意吗?
有其他替代方法吗?

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?

推荐答案

在JSP/Servlet Web应用程序中手动生成非托管线程绝对不是一个好主意.肯定不能在JSP端完成时这样做,因为它在任何方面都不符合JSP的职责.

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.

线程是一种相对危险的资源,需要格外小心.想象一下,您的JSP在每个请求上都产生一个新线程,然后您的Web服务器将在例如1000个请求后被杀死.您需要重新启动它.

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.

即使以每个用户为基础适当地控制线程的使用和终止,您仍然需要确保单个访问者不能在整个会话范围内产生多个线程.但是,例如,当您同时进行1000个会话时,您的服务器仍将被杀死.

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.

您想要一个应用程序范围的共享线程池,而不是最多10到20个线程之类的锁.通常,已经有一些不错的Java EE容器了.您需要检查其管理控制台和/或其手册,以了解如何配置和使用它.最终,您还可以自己在例如ServletContextListener中的ExecutorService的帮助下创建一个线程池,但是您应该非常了解线程如何工作以及如果做错了可能带来的影响.

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

这篇关于我可以在JSP中生成新线程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆