首页 > 解决方案 > scala - 如何为期货、并行收集和 akka 创建共享线程池/执行上下文

问题描述

我想在我的应用程序中定义 2 个线程池。一个 fork-join 和一个线程池执行器。此外,每个池应该能够由 Akka 演员、Scala 期货和 Scala 并行集合共享。

对于未来,scala 需要范围内的执行上下文,并且可以通过以下方式之一创建:

implicit val ec = ExecutionContext.global //want to avoid this
import scala.concurrent.ExecutionContext.Implicits.global //want to avoid this
implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(64))
implicit val ec = ExecutionContext.fromExecutor(Executors.newForkJoinThreadPool(64))

对于并行集合,您必须TaskSupport像这样修改

val forkJoinPool = new java.util.concurrent.ForkJoinPool(64)
parArray.tasksupport = new ForkJoinTaskSupport(forkJoinPool)

有了上面,我唯一的选择是val forkJoinPool = new java.util.concurrent.ForkJoinPool(64)在我的应用程序中全局定义并将其用于两者。

但是,我不知道如何为 Akka 演员使用同一个池。对于 Akka,我看到至少以下两种自定义池的方法。

val actorSysterm = ActorSystem.create("hello-system", config.getConfig("my-dispatcher”)) 
implicit val executionContext = actorSysterm.dispatcher

implicit val system = ActorSystem()
implicit val executionContext = actorSysterm.dispatchers.lookup("my-dispatcher")

这是基于配置文件的。

my-dispatcher {
  type = Dispatcher
  executor = "fork-join-executor"
  fork-join-executor {
    parallelism-min = 8
    parallelism-factor = 2.0
    parallelism-max = 64
  }
  throughput = 100
}
blocking-io-dispatcher {
  type = Dispatcher
  executor = "thread-pool-executor"
  thread-pool-executor {
    fixed-pool-size = 32
  }
  throughput = 1
}

我更喜欢创建 Akka,ExecutionContext因为现在我可以在 hocon(json) 文件中配置我的池,也可以在 play framework 应用程序中使用它。我可以将它与 ScalaFutures一起使用,但现在如何将它与 Scala Parallel 集合一起使用?有没有办法访问底层池,ExecutionContext以便我可以使用它来初始化TaskSupport并行集合?

标签: scalaakka

解决方案


TaskSupport我之前忽略了并行集合使用的另一种实现。有了它,我可以使用与executionContextFuture 和 ActorSystem 相同的方法。

pc.tasksupport = new ExecutionContextTaskSupport(executionContext)


推荐阅读