如何分配线程来处理 Servlet 请求? [英] How are Threads allocated to handle Servlet request?

查看:26
本文介绍了如何分配线程来处理 Servlet 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下什么是每个请求的线程和每个连接的线程?servlet 在哪种模型上工作?如何分配线程来处理 HTTP 请求?是线程/请求还是连接?

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?

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

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.

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

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?

推荐答案

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

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.

在另一个线程中创建一个线程并没有建立任何特殊的关系,在大多数情况下这样做的重点是让一个线程做更多的工作或终止而另一个线程继续工作.在您的场景中,使用不同的线程来完成请求所需的工作,如您所料,将允许立即发送响应.用于为该请求提供服务的线程也将立即可用于另一个请求,无论您的另一个线程需要多长时间才能完成.这几乎是在每请求一个线程的 servlet 容器中进行异步工作的方式.

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.

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

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.

这篇关于如何分配线程来处理 Servlet 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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