我应该限制我拥有的执行者数量吗?
我有一个 Java 项目,需要并行运行。我和执行者一起做这件事。问题是,我需要在很多地方使用执行器。我应该赞成传递一些执行程序来完成工作(暂时忘记限制全局线程数),还是最好在我需要的地方创建执行程序?
I have a Java project where I need to run things in parallel. I do this with executors. The thing is, I need to use executors in a great many places. Should I favor passing a few executors around to do the work (forget about limiting the global number of threads for a moment) or is it preferable to create the executors where I need them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您真正需要考虑的是控制您创建的任何执行程序的线程数量。
您在每个执行器上创建的线程数量将是每个提交任务的到达频率和预期持续时间(处理时间)的函数。每个逻辑任务类型都有一个队列,允许您调整该任务的执行器,这样您就不会拥有超出所需的线程,并且您始终可以跟上预期的任务吞吐量。
如果您在应用程序的所有处理阶段共享一个整体执行器,那么调优就会变得更加困难。
SEDA 是一种典型的并发模式,反映了每个处理阶段排队的原则。
在某些情况下,拥有一个共享执行器确实有意义,例如对于不频繁的、临时的或低优先级的计划任务。
What you really need to think about is controlling the number of Threads working off any Executors you create.
The number of threads you create off each executor will be a function of the frequency of arrival and expected duration (processing time) of each task being submitted. Having a queue per logical task type allows you to tune the executor for just that task, so that you don't have more threads than required, and you can always keep up with the expected task throughput.
If you have one monolithic Executor shared across all processing stages in your app it becomes much harder to tune.
SEDA is a typical concurrency pattern that reflects this principle of queue per processing stage.
In some instances it does make sense to have a shared executor, such as for infrequent, ad-hoc or low priority scheduled tasks.
没有严格的规则告诉您应该使用多少个执行程序。不过可以推荐一件事。使用一些依赖注入机制或框架来注入执行器实现。这将允许快速、轻松地更换和配置使用过的执行器。
There's no strict rule that will tell you how many executors should be used. One thing, though can be recommended. Use some dependency injection mechanism or framework to inject executor implementations. This will allow quick and easy replacement and configuration of used executors.