尽管有Await.result,我如何保持固定大小的线程池固定大小?

时间:2017-02-21 14:34:12

标签: multithreading scala async-await threadpool executorservice

如何防止ExecutionContext的内部线程池大小在以下用例中增长?

1。执行上下文

  val par = 64    // thread pool size
  implicit override def executionContext: ExecutionContextExecutorService = ExecutionContext.fromExecutorService(
    java.util.concurrent.Executors.newFixedThreadPool(par),
    t => {
      System.err.println("Exception in child thread: " + t.getMessage)
      t.printStackTrace()
      throw t
    })

2。很多Future s(但小于2*par

val futureList = ArrayBuffer[Future[Int]]()
...
futureList += Future { ... }

第3。等待

futureList.foreach(Await.result(_, Duration.Inf))
futureList.clear()

4。超出操作系统线程限制

Exception in thread "pool-1896-thread-1" java.lang.OutOfMemoryError: unable to create new native thread
    at java.lang.Thread.start0(Native Method)
    at java.lang.Thread.start(Thread.java:714)
    at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:950)
    at java.util.concurrent.ThreadPoolExecutor.processWorkerExit(ThreadPoolExecutor.java:1018)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1160)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

我希望这个固定的线程池大小真正保持固定!我该怎么做?

Future的数量小于2*par,但此函数(2-3)执行16次(按顺序),因此Future的总数s更大。但隐式executionContext(如1中所定义)是相同的。

谢谢!

0 个答案:

没有答案