java 在 servlet 中启动一个新线程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10330104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:36:23  来源:igfitidea点击:

starting a new thread in servlet

javamultithreadingservletsweb

提问by saplingPro

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.

当请求到达处理文件上传的 servlet 时,是否最好在该 servlet 中启动一个新线程,该线程new Thread(r).start()将处理上传的文件附带的另一条数据。我想以此并行处理这两项工作。

回答by Tomasz Nurkiewicz

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.

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

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

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

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 cando 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 3.0 异步请求并异步处理上传,但最好使用一些线程池。另请参阅:为什么使用 startAsync 创建新线程而不是在 servlet 线程中工作?.

回答by Akash Yadav

Servlets are implicitly run in new threads by webserver, so whenever any request hits a servlet , it will be executed in a different thread. i dont foresee a reason to create a fresh thread yourself

servlet 由 web 服务器隐式地在新线程中运行,因此每当任何请求命中 servlet 时,它将在不同的线程中执行。我没有预见到自己创建一个新线程的理由

回答by Piotr Kochański

There is nothing wrong in starting new thread in Servlet (unlike EJB), so yes, it is ok.

在 Servlet 中启动新线程没有错(与 EJB 不同),所以是的,没问题。

EDIT: second thought @Tomasz Nurkiewicz is right. The file upload will be stopped.

编辑:第二个想法@Tomasz Nurkiewicz 是对的。文件上传将停止。