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

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

问题描述

当请求到达处理文件上传的 servlet 时,使用 new Thread(r).start() 在该 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.

推荐答案

这不仅是个坏主意,而且也行不通.原因如下:您的文件上传请求最终会命中 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天全站免登陆