码迷,mamicode.com
首页 > 编程语言 > 详细

Scala中Future的线程数

时间:2015-07-22 13:26:33      阅读:737      评论:0      收藏:0      [点我收藏+]

标签:

为什么Future最大只有4个并发线程?
线程池中有多少个线程是由ExecutionContext决定的。如果使用的是默认的global,则只有4个并发线程。
import scala.concurrent.ExecutionContext.Implicits.global

默认的global ExecutionContext在哪里设置的4个并发线程?
global用的是ExecutionContextImpl,其中有这么一段代码:
  1. def createExecutorService: ExecutorService = {
  2. def getInt(name: String, f: String => Int): Int =
  3. try f(System.getProperty(name)) catch { case e: Exception => Runtime.getRuntime.availableProcessors }
  4. def range(floor: Int, desired: Int, ceiling: Int): Int =
  5. if (ceiling < floor) range(ceiling, desired, floor) else scala.math.min(scala.math.max(desired, floor), ceiling)
  6. val desiredParallelism = range(
  7. getInt("scala.concurrent.context.minThreads", _.toInt),
  8. getInt("scala.concurrent.context.numThreads", {
  9. case null | "" => Runtime.getRuntime.availableProcessors
  10. case s if s.charAt(0) == ‘x‘ => (Runtime.getRuntime.availableProcessors * s.substring(1).toDouble).ceil.toInt
  11. case other => other.toInt
  12. }),
  13. getInt("scala.concurrent.context.maxThreads", _.toInt))
  14. val threadFactory = new DefaultThreadFactory(daemonic = true)
  15. try {
  16. new ForkJoinPool(
  17. desiredParallelism,
  18. threadFactory,
  19. uncaughtExceptionHandler,
  20. true) // Async all the way baby
  21. } catch {
庄家ForkJoinPool时设定了desiredParallelism。可以看到desiredParallelism函数得到并行度有多少是根据系统变量来的(注意getInt函数):
scala.concurrent.context.minThreads:最小并发线程数(Int)
scala.concurrent.context.numThreads:并发线程数,如果是Int,则就使用这个值;如果是String,并且以“x”开头,后面跟个Double(如“x1.5”),则其值为1.5 * Runtime.getRuntime.availableProcessors
scala.concurrent.context.maxThreads:最大并发线程数(Int)

如果这三个变量没有设置,则getInt会取Runtime.getRuntime.availableProcessors,即当前CPU的核数。所以,在我的电脑上只有4个并发线程运行Future.

怎么改变Future的并发线程数?
1. 从上面的代码分析可以很容易想到,如果仍使用global ExecutionContext,修改系统变量即可:
  1. System.setProperty("scala.concurrent.context.minThreads", "8")
  2. System.setProperty("scala.concurrent.context.maxThreads", "8")

2. 更好的方法是重写一个自己的ExecutionContext。
  1. import java.util.concurrent.Executors
  2. import scala.concurrent._
  3. implicit val ec = new ExecutionContext {
  4. val threadPool = Executors.newFixedThreadPool(1000);
  5. def execute(runnable: Runnable) {
  6. threadPool.submit(runnable)
  7. }
  8. def reportFailure(t: Throwable) {}
  9. }











Scala中Future的线程数

标签:

原文地址:http://my.oschina.net/guanxun/blog/482089

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!