2017-09-11 48 views
-1

我知道Akka調度程序與全局執行上下文之間的基本區別。Akka執行上下文與未來全局上下文

我嘗試這個代碼與scala.concurrent.ExecutionContext.Implicits.global

import scala.concurrent.ExecutionContext.Implicits.global 
    val resultF = (0 to 100).map(
    x => 
     Future { 
     val startTime = System.currentTimeMillis() 
     val task = Future { 
      Thread.sleep(100) 
      x 
     } 
     task.onSuccess { 
      case result => 
      val timeRemaining = System.currentTimeMillis() - startTime 
      println(s"$result $timeRemaining") 
     } 
    } 
) 
    StdIn.readLine() 

上述代碼打印上的平均值)的時間等於了Thread.sleep(,周圍103毫秒的平均。

但是下面的代碼打印100-400毫秒之間的時間。

val system = ActorSystem("test") 
    implicit val executionContext = system.dispatcher 
    val resultF = (0 to 100).map(
    x => 
     Future { 
     val startTime = System.currentTimeMillis() 
     val task = Future { 
      Thread.sleep(100) 
      x 
     } 
     task.onSuccess { 
      case result => 
      val timeRemaining = System.currentTimeMillis() - startTime 
      println(s"$result $timeRemaining") 
     } 
    } 
) 
    StdIn.readLine() 

我不理解什麼是除了使用thread-pool的主要區別。

+1

沒有更精確的問題... http://doc.akka.io/docs/akka/2.5/scala/dispatchers.html – cchantep

+0

@cchantep我很瞭解調度員,但我不是肯定爲什麼在上面兩個代碼片段中有這麼多差異。 – Atiq

回答

0

我不明白除了使用的線程池之外,主要區別是什麼。

唯一的區別是使用的線程池及其工作調度算法。

的阿卡ActorSystem線程池是一個的fork-join執行,截至http://doc.akka.io/docs/akka/2.5/scala/dispatchers.html

「全局」默認的ExecutionContext描述一個工作竊取線程池,例如見https://github.com/scala/scala/blob/v2.12.3/src/library/scala/concurrent/ExecutionContext.scala#L135

參見例如, How is the fork/join framework better than a thread pool?