当通过ExecutorCompletionService执行时,任务是否并行化? [英] Are tasks parallelized when executed via an ExecutorCompletionService?

查看:279
本文介绍了当通过ExecutorCompletionService执行时,任务是否并行化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我向 ExecutorCompletionService提交了5个工作,但它似乎像工作按顺序执行。传递给 ExecutorCompletionService的构造函数的ExecutorService 使用newCacheThreadPool表单创建。我做错了什么?

I submitted 5 jobs to an ExecutorCompletionService, but it seems like the jobs are executed in sequence. The ExecutorService that is passed to the constructor of ExecutorCompletionService is created using newCacheThreadPool form. Am I doing anything wrong ?

UPDATE 每个作业基本上都在进行数据库查询。一些计算。 ExecutorCompletionService的代码被取消了javadoc。

UPDATE Each job is basically doing a database query & some calculation. The code for the ExecutorCompletionService is lifted as-is off the javadoc. I just replaced the Callables with my own custom Callable implementations.

推荐答案

ExecutorCompletionService

The ExecutorCompletionService has nothing to do with how jobs are executed, it's simply a convenient way of retrieving the results.


  • 任务是独立的,不要例如在同一个对象上同步;

  • 您有多个硬件CPU线程。

最后一点值得解释。虽然没有保证,在实践中,Sun JVM喜欢当前正在执行的线程,所以它从来没有被换出来支持另一个。这意味着您的5个任务可能最终由于JVM实现而没有顺序执行。多核机器。

The last point deserves an explanation. Although there are no guarantees, in practice the Sun JVM favours the currently executing thread so it's never swapped out in favour of another one. That means that your 5 tasks might end up being executed serially due to the JVM implementation and not having e.g. a multi-core machine.

这篇关于当通过ExecutorCompletionService执行时,任务是否并行化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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