是否将隐式执行上下文传递给.par操作?

时间:2018-09-22 10:40:11

标签: scala concurrency parallel-processing executioncontext

我有这种情况:

  • 方法a:创建一个隐式ec

  • 方法a:在Future中调用另一个方法,即Future(anotherMethod)anotherMethod,其所有后续调用在作用域中都不再具有方法a中的ec。

示例代码:

class Foo {
  private implicit val ec: ExecutionContextExecutor =
        ExecutionContext.fromExecutor(Executors.newFixedThreadPool(Runtime.getRuntime.availableProcessors()))

  private val anotherClass = new Bar()

  def methodA() = Future(anotherClass.anotherMethod())
}

我猜测,从.parsomeVector.par.map.().seq的任何调用,例如anotherMethod等,或其任何后续调用,都将使用全局执行上下文,而不是自定义的上下文在方法a中创建。我的假设正确吗?

1 个答案:

答案 0 :(得分:4)

  

我猜想,从anotherMethod或其任何后续调用中对.par的任何调用(例如someVector.par.map。()。seq等)都将使用全局执行上下文,而不是使用在其中创建的自定义上下文方法一我的假设正确吗?

让我们将这个答案一分为二。首先,如果您的调用链中还有其他任何需要隐式ExecutionContext的方法,它们将在您的顶级methodA调用中隐式定义一个方法。

否则,Scala中的并行集合设计没有ExecutionContext的概念,这严格是Future的属性。并行集合库的概念为TaskSupport,它负责在并行集合内部进行调度:

*  Parallel collections are modular in the way operations are scheduled. Each
*  parallel collection is parameterized with a task support object which is
*  responsible for scheduling and load-balancing tasks to processors.

因此,这些并行集合与ExecutionContext中声明的Foo没有任何关系。但是,您可以通过tasksupport设置器来明确设置它们:

val par = List(1,2,3,4).par
par.tasksupport = new ForkJoinTaskSupport(new ForkJoinPool(4))
相关问题