Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

starting a new thread in servlet

When a request reaches a servlet that handles uploading of files,is it a good idea to start a new thread in that servlet using new Thread(r).start() that will handle another piece of data that came with the file that was uploaded. I wanted to this to handle both the jobs parallely.

like image 483
saplingPro Avatar asked Apr 26 '12 08:04

saplingPro


People also ask

When a thread is created in Servlet?

When a request comes in, a Thread is acquired from the pool to handle it. When the request is finished and a response is sent back, the Thread is returned to the pool and is available for future requests. It has nothing to do with the http session and doesn't matter which Servlet is involved.

Is http request a thread?

An HTTP request is processed by a thread. A thread, in turn, can handle a number of network connections. You can specify the number of threads the Web server can process. In general, the number of threads specified is an indication of the number of users who can access the server simultaneously.


1 Answers

It is not only a bad idea, but it also won't work. Here is why: your file upload request will eventually hit doPost() method. As long as you are in this method, the container keeps the connection open. Once you return from that method (and if you decide to handle incoming data in a separate thread, doPost() will finish early) the container assumes you are done with the request and will close the connection. From the client perspective the upload was interrupted by the server. And because of the asynchronous nature of threads the interruption will occur in random moment.

Believe me, some users already experienced that: HttpServletResponse seems to periodically send prematurely.

Moreover it is a bad idea to start new thread per request as this scales poorly (and it is even prohibited by some specifications). What you can do is to use Servlet 3.0 asynchronous request and handle uploads asynchronously, but preferably using some pool of threads. See also: Why create new thread with startAsync instead of doing work in servlet thread?.

like image 168
Tomasz Nurkiewicz Avatar answered Sep 27 '22 22:09

Tomasz Nurkiewicz