Scala Futures没有并行运行

时间:2014-12-01 03:50:05

标签: scala

我有一个非常简单的Maven spring MVC项目,我添加了Scala。我希望以下三个期货能够按预期同时执行。然而,他们一个接一个地执行

val viewName: Future[String] = for {
  profileSync <- Future { EmployeeLocalServiceUtil.syncProfileInformation() }
  earningsSync <- Future { EmployeeLocalServiceUtil.syncEarnings() }
  reimbursementSync <- Future { EmployeeLocalServiceUtil.syncReimbursements() }
} yield {
  "employee/view"
}

我的机器有4个核心,我正在使用scala.concurrent.ExecutionContext.Implicits.global上下文。除此之外,没有任何配置可以阻止/启用期货的并行执行。

1 个答案:

答案 0 :(得分:8)

因为理解只是语法糖而且是translated to flatMap like in Example 2

这意味着您的代码大致如下所示:

Future { ??? }.flatMap { profileSync =>
  Future { ??? }.flatMap { earningsSync =>
    Future { ??? }.map { reimbursementSync =>
       // Able to access profileSync/earningsSync/reimbursementSync values.
       "employee/view"
    }
  }
}

如您所见Future仅在上一次完成后才启动。首先开始你的Future然后进行理解:

val profileSyncFuture = Future {  EmployeeLocalServiceUtil.syncProfileInformation()      }
val earningsSyncFuture = Future {  EmployeeLocalServiceUtil.syncEarnings()      }
val reimbursementSyncFuture = Future {  EmployeeLocalServiceUtil.syncReimbursements()      }

val viewName: Future[String] = for {
  profileSync <- profileSyncFuture 
  earningsSync <- earningsSyncFuture 
  reimbursementSync <- reimbursementSyncFuture 
} yield {
    "employee/view"
}