隐式执行上下文是否传递给 .par 操作?
Is an implicit execution context passed down to .par operations?
我遇到这种情况:
方法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())
}
我猜,任何对 .par
的调用,例如 someVector.par.map.().seq
等,来自 anotherMethod
或其任何后续调用,都将使用全局执行上下文,而不是自定义一个在方法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?
让我们把这个答案一分为二。首先,如果您的调用链中有任何其他方法需要隐式 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.
因此这些并行集合将与 Foo
中声明的 ExecutionContext
没有任何关系。但是,您可以通过 tasksupport
setter:
显式设置它们
val par = List(1,2,3,4).par
par.tasksupport = new ForkJoinTaskSupport(new ForkJoinPool(4))
我遇到这种情况:
方法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())
}
我猜,任何对 .par
的调用,例如 someVector.par.map.().seq
等,来自 anotherMethod
或其任何后续调用,都将使用全局执行上下文,而不是自定义一个在方法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?
让我们把这个答案一分为二。首先,如果您的调用链中有任何其他方法需要隐式 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.
因此这些并行集合将与 Foo
中声明的 ExecutionContext
没有任何关系。但是,您可以通过 tasksupport
setter:
val par = List(1,2,3,4).par
par.tasksupport = new ForkJoinTaskSupport(new ForkJoinPool(4))