val nestedFuture: Future[Future[Boolean]] = heatWater(Water(25)).map { water => temperatureOkay(water) } val flatFuture: Future[Boolean] = heatWater(Water(25)).flatMap { water => temperatureOkay(water) }
多个 Future 的链合并的另一种方式:
val f = for { result1 <- remoteCall1 result2 <- remoteCall2 } yield List(result1, result2)
假如 future 定义在 for 之前则会并发执行,否则会顺序执行。另外,假如顺序执行 result1 可以作为参数传递到 remoteCall2 中。
implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10))
假如熟悉 Java 线程池的话,线程池的创建和 Java 中完全一样,可以套用。
Scala & Akka 中的 Dispatcher 定义一个 Dispatcher:
my-dispatcher { # Dispatcher is the name of the event-based dispatcher type = Dispatcher # What kind of ExecutionService to use executor = "fork-join-executor" # Configuration for the fork join pool fork-join-executor { # Min number of threads to cap factor-based parallelism number to parallelism-min = 2 # Parallelism (threads) ... ceil(available processors * factor) parallelism-factor = 2.0 # Max number of threads to cap factor-based parallelism number to parallelism-max = 10 } # Throughput defines the maximum number of messages to be # processed per actor before the thread jumps to the next actor. # Set to 1 for as fair as possible. throughput = 100 }
或者这样:
my-thread-pool-dispatcher { # Dispatcher is the name of the event-based dispatcher type = Dispatcher # What kind of ExecutionService to use executor = "thread-pool-executor" # Configuration for the thread pool thread-pool-executor { # minimum number of threads to cap factor-based core number to core-pool-size-min = 2 # No of core threads ... ceil(available processors * factor) core-pool-size-factor = 2.0 # maximum number of threads to cap factor-based number to core-pool-size-max = 10 } # Throughput defines the maximum number of messages to be # processed per actor before the thread jumps to the next actor. # Set to 1 for as fair as possible. throughput = 100 }
在 Scala 代码中引用引用之前定义的 Dispatcher:
implicit val executionContext = system.dispatchers.lookup("my-dispatcher")
给某个 Actor 指定 dispatcher:
val myActor = context.actorOf(Props[MyActor].withDispatcher("my-dispatcher"), "myactor1")