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.
When a request reaches a servlet that handles uploading of files,is it a good
Share
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?.