http请求和线程池
我有这个问题。为了创建单个 http 请求的响应,我必须执行多个可以同时执行的任务。我可以在执行器(线程池)中执行这些任务,但随后我必须担心网络应用程序中的并发(同步)问题。有没有更好的方法来解决这个问题而不使用线程池?
谢谢,
I have this problem. In order to create a response for a single http request, I have to do several tasks that can be performed concurrently. I can perform those tasks in a Executor (thread pool) but then I have to worry about concurrency (synchronization) in my web app. Is there a better way to solve this problem without using thread pool?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 Executor 可以处理线程同步的混乱细节,因此它应该是并发执行多个任务的最简单方法。您只需将作业提交给执行器并等待它们完成。
如果这些后台任务访问某些共享资源(特别是内存中的数据结构),则需要协调这种访问。最简单的方法是避免共享资源,但是否可以做到这一点取决于您实际需要做什么。如果必须具有共享资源,则可以使用 Java 同步原语或并发包中的一些其他实用程序。
你不能拥有多个线程而不考虑同步。
这里没有灵丹妙药。
(顺便说一句,即使单个 Web 请求没有多个线程,您也可能必须考虑 Web 应用程序中的线程问题,因为同一个 Web 服务器可能会同时受到多个请求的影响)。
Using an Executor takes care of the messy details of thread synchronization, so it should be the easiest way to perform multiple tasks concurrently. You just submit jobs to the executor and wait for them to finish.
If these background tasks access some shared resource (especially in-memory data structures), then this access needs to be coordinated. The easiest way is to avoid shared resources, but if you can do that depends on what you actually need to do. If you must have shared resources, you can use Java synchronization primitives, or some other utilities from the concurrency package.
You cannot have multiple threads and not think about synchronization.
No silver bullet here.
(By the way, even without multiple threads for a single web request, you probably have to consider threading issues in a web application anyway, because the same web server can be hit by multiple requests simultaneously).