在servlet中启动一个新线程 [英] starting a new thread in servlet

查看:780
本文介绍了在servlet中启动一个新线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当请求到达处理文件上传的servlet时,最好使用 new Thread(r).start()它将处理上传文件附带的另一段数据。我希望这能同时处理这两个工作。

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.

推荐答案

这不仅是一个坏主意,但它也不会工作。原因如下:您的文件上传请求最终将达到 doPost()方法。只要您使用此方法,容器就会保持连接打开状态。从该方法返回后(如果您决定在单独的线程中处理传入数据, doPost()将提前完成)容器假定您已完成请求并且将关闭连接。从客户端的角度来看,服务器中断了上传。并且由于线程的异步性质,中断将在随机时刻发生。

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.

相信我,一些用户已经经历过: HttpServletResponse似乎会过早定期发送

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

此外,根据请求启动新线程是一个坏主意(某些规格甚至禁止它)。你可以做的是使用Servlet 3.0异步请求并异步处理上传,但最好使用一些线程池。另请参阅:为什么使用startAsync创建新线程而不是在servlet线程中工作?

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?.

这篇关于在servlet中启动一个新线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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