是否将隐式执行上下文传递给.par操作? [英] Is an implicit execution context passed down to .par operations?

查看:92
本文介绍了是否将隐式执行上下文传递给.par操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种情况:

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

  • method a: an implicit ec is created

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

method a: calls another method in a Future, i.e Future(anotherMethod). anotherMethod, and all its subsequent calls no longer have the ec from method a in scope.

示例代码:

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

  private val anotherClass = new Bar()

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

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

I'm guessing, that any calls to .par, e.g someVector.par.map.().seq etc, from anotherMethod or any of its subsequent calls, will use the global execution context and not the custom one created in method a. Is my assumption correct?

推荐答案

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

I'm guessing, that any calls to .par, e.g someVector.par.map.().seq etc, from anotherMethod or any of its subsequent calls, will use the global execution context and not the custom one created in method a. Is my assumption correct?

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

Let's split this answer in two. First, if you have any other methods in your call chain that will require an implicit ExecutionContext, they will get the one implicitly defined inside your top level methodA call.

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

Otherwise, the parallel collection design in Scala has no notion of an ExecutionContext, that is strictly a property of Future. The parallel collection library has a notion of a TaskSupport which is responsible for scheduling inside the parallel collection:

*  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.

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

So these parallel collections will not have anything to do with the ExecutionContext declared in Foo. You can, however, explicitly set them via the tasksupport setter:

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

这篇关于是否将隐式执行上下文传递给.par操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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