代码之家  ›  专栏  ›  技术社区  ›  Ali

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

  •  0
  • Ali  · 技术社区  · 6 年前

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

    • 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 恒温法 或其任何后续调用将使用全局执行上下文,而不是在方法a中创建的自定义上下文。我的假设正确吗?

    1 回复  |  直到 6 年前
        1
  •  5
  •   Yuval Itzchakov    6 年前

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

    让我们把这个答案一分为二。首先,如果调用链中有任何其他方法需要隐式 ExecutionContext methodA

    否则,Scala中的并行集合设计没有 执行上下文 ,这是严格意义上的 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 tasksupport 设定者:

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