How are threads allocated to handle a Servlet request?

Can someone explain what a request stream and connection stream are? What model do servlets work on? How are threads allocated to handle HTTP requests? Is it a stream / request or connection?

And let me say that if I want to perform the time-consuming task in my Servlet doGet() method asynchronously, I start a new thread using Java executors so that lengthy calculations are performed in a separate thread and the response is sent immediately.

Now does it guarantee that I freed the thread that my HttpServletRequest processing, or is it still in use because the child thread is still running?

+35
java java-ee multithreading threadpool servlets
Sep 17 '11 at 19:17
source share
1 answer

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

Creating a thread inside another thread does not establish any special relationship, and in most cases this is done if one thread is working more or is completed while the other thread continues to work. In your scenario, using another thread to do the work required by the request will, as you expect, allow you to immediately send a response. The thread used to service this request will also be immediately available for another request, no matter how long your other thread takes. This is pretty much a way of doing asynchronous work in a stream servlet container per request.

Caution: If you are in a full Java EE container, threads can be managed for you in such a way as to create a bad idea, to create your own. In this case, you better ask the container for the stream, but the general principles are the same.

+39
Sep 17 '11 at 19:28
source share



All Articles