我知道 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
之外的主要区别是什么使用过。
最佳答案
I'm failing to understand what's the major difference apart from thread-pool used.
唯一的区别是使用的线程池及其工作调度算法。
Akka 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?
关于scala - Akka 执行上下文与 Future 全局上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46159267/