如何分配线程来处理 Servlet 请求?

发布于 2024-12-05 09:21:07 字数 272 浏览 1 评论 0原文

有人可以解释一下什么是每个请求线程和每个连接线程吗? servlet 适用于哪种模型?如何分配线程来处理 HTTP 请求?是线程/请求还是连接?

假设我想在 ServletdoGet() 方法中异步执行一项耗时的任务,我会使用 Java 执行器启动一个新线程,以便进行冗长的计算在单独的线程中完成并立即发送响应。

现在,这是否确保我已经释放了正在处理我的 HttpServletRequest 的线程,或者它仍然被使用,因为子线程仍在运行?

Can someone please explain what is thread per request and thread per connection? Which model do servlets work on? How threads are allocated to handle HTTP requests? Is it thread/request or connection?

And let's say if I want to perform a time consuming task in my Servlet's doGet() method asynchronously, I start a new thread using Java executors so that lengthy calculations are done in a separate thread and response is sent right away.

Now does that ensure that I have freed the thread which had been processing my HttpServletRequest or is it still being used because a child thread is still running?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戏剧牡丹亭 2024-12-12 09:21:07

每个请求意味着当发出 HTTP 请求时,会创建一个线程或从池中检索一个线程来为其提供服务。一个线程处理整个请求。每个连接的线程是相同的,只是该线程用于整个连接,这可能是多个请求,并且请求之间也可能有很多死区时间。 Servlet 容器是每个请求的线程。可能有一些实现为每个连接提供线程,但我不知道,而且看起来这会非常浪费。

在另一个线程中创建一个线程不会建立任何特殊关系,在大多数情况下这样做的全部目的是让一个线程执行更多工作或在另一个线程继续工作时终止。在您的场景中,使用不同的线程来完成请求所需的工作将如您所期望的那样,允许立即发送响应。用于服务该请求的线程也将立即可用于另一个请求,无论其他线程需要多长时间才能完成。这几乎就是在每个请求一个线程的 Servlet 容器中执行异步工作的方式。

警告:如果您处于完整的 Java EE 容器中,则可能会以某种方式为您管理线程,因此生成您自己的线程是一个坏主意。在这种情况下,您最好向容器请求线程,但一般原则是相同的。

Per request means when an HTTP request is made, a thread is created or retrieved from a pool to serve it. One thread serves the whole request. Thread per connection would be the same thing except the thread is used for an entire connection, which could be multiple requests and could also have a lot of dead time in between requests. Servlet containers are thread per request. There may be some implementations that offer thread per connection, but I don't know, and it seems like it would be very wasteful.

Creating a thread inside another thread doesn't establish any special relationship, and the whole point of doing so in most cases is to let the one thread do more work or terminate while the other thread continues working. In your scenario, using a different thread to do work required by a request will, as you expect, allow the response to be sent immediately. The thread used to serve that request will also be immediately available for another request, regardless of how long your other thread takes to complete. This is pretty much the way of doing asynchronous work in a thread-per-request servlet container.

Caveat: If you're in a full Java EE container, threads may be managed for you in a way that makes it a bad idea to spawn your own. In that case, you're better off asking the container for a thread, but the general principles are the same.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文