How to configure a fine tuned thread pool for futu

2019-01-08 04:25发布

How large is Scala's thread pool for futures?

My Scala application makes many millions of future {}s and I wonder if there is anything I can do to optimize them by configuring a thread pool.

Thank you.

3条回答
萌系小妹纸
2楼-- · 2019-01-08 04:49

You can specify your own ExecutionContext that your futures will run in, instead of importing the global implicit 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) {}
}
查看更多
Explosion°爆炸
3楼-- · 2019-01-08 04:52

best way to specify threadpool in scala futures:

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();
    }
查看更多
别忘想泡老子
4楼-- · 2019-01-08 05:08

This answer is from monkjack, a comment from the accepted answer. However, one can miss this great answer so I'm reposting it here.

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

If you just need to change the thread pool count, just use the global executor and pass the following system properties.

-Dscala.concurrent.context.numThreads=8 -Dscala.concurrent.context.maxThreads=8
查看更多
登录 后发表回答