scala - Akka 执行上下文与 Future 全局上下文

标签 scala akka threadpool

我知道 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/

相关文章:

java - 如何编写java线程池程序来读取文件内容?

java - 管理 Akka Actor 系统生命周期

scala - Akka:在集成测试中模拟组件的策略

scala - 是否可以在 Actor 内发出 Akka HTTP 核心客户端请求?

scala - Spark 上的应用程序网络?

c# - Task.Run(()=> DoWorkAsync()) 和 new Thread(async()=> DoWorkAsync()); 之间的区别

c++ - 在 QThreadPool 中执行槽

scala - 中断 Future 映射链并返回一个 Left

scala - 如何使用 Spark 确定分区键/列

performance - 为什么电梯框架这么慢?