如何调整akka线程池以拒绝完整线程池和任务队列中的新任务?

时间:2016-07-01 14:46:20

标签: multithreading scala akka threadpool

我想使用akka线程池来执行一些资源有限的并行任务,如果有太多任务我希望它们被拒绝。

我有以下调度程序配置了akka

my-dispatcher {
  type = Dispatcher
  executor = thread-pool-executor
  thread-pool-executor {
    core-pool-size-min = 1
    core-pool-size-max = 2
    task-queue-size = 5
  }
}

以下代码

import java.time.LocalTime

import akka.actor.ActorSystem

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

object Main {

  def main(args: Array[String]) {
    val system = ActorSystem("my-system")
    implicit val dispatcher = system.dispatchers.lookup("my-dispatcher")

    for (_ <- 1 to 10) Future {
      Thread.sleep(5000)
      println(s"Finished at ${ LocalTime.now }")
    }

    Await.result(system.terminate(), Duration.Inf)
  }

}

我预计在线程池耗尽空闲线程(最大大小为2)并且任务队列也已满(5个元素)之后 - 它将拒绝新的期货。但是,这就是我所看到的:

Finished at 17:36:57.858
Finished at 17:36:57.858
Finished at 17:36:57.858
Finished at 17:36:57.858
Finished at 17:36:57.858
Finished at 17:37:02.870
Finished at 17:37:02.870
Finished at 17:37:02.870
Finished at 17:37:02.870
Finished at 17:37:02.870

因此,它调用前5个任务,几乎同时完成它们(17:36:57),并且在17:37:02暂停5秒(Thread.sleep(5000))后完成第二部分任务。这意味着当队列已满并且线程池完全忙碌时 - Future.apply(???)调用只会阻塞,而不是拒绝新的未来。我希望看到某种RejectionException或类似的东西。

如何使用akka实现此行为?

0 个答案:

没有答案