如何为期货配置微调线程池?

问题描述 投票:75回答:3

Scala的期货线程池有多大?

我的Scala应用程序生成了数百万个future {}s,我想知道我是否可以通过配置线程池来优化它们。

谢谢。

multithreading scala parallel-processing threadpool future
3个回答
86
投票

您可以指定您的期货将运行的自己的ExecutionContext,而不是导入全局隐式ExecutionContext。

import java.util.concurrent.Executors
import scala.concurrent._

implicit val ec = new ExecutionContext {
    val threadPool = Executors.newFixedThreadPool(1000)

    def execute(runnable: Runnable) {
        threadPool.submit(runnable)
    }

    def reportFailure(t: Throwable) {}
}

135
投票

这个答案来自monkjack,来自公认答案的评论。然而,人们可以错过这个伟大的答案,所以我在这里重新发布。

implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10))

如果您只需要更改线程池计数,只需使用全局执行程序并传递以下系统属性。

-Dscala.concurrent.context.numThreads=8 -Dscala.concurrent.context.maxThreads=8

3
投票

在scala期货中指定threadpool的最佳方法:

implicit val ec = new ExecutionContext {
      val threadPool = Executors.newFixedThreadPool(conf.getInt("5"));
      override def reportFailure(cause: Throwable): Unit = {};
      override def execute(runnable: Runnable): Unit = threadPool.submit(runnable);
      def shutdown() = threadPool.shutdown();
    }
© www.soinside.com 2019 - 2024. All rights reserved.