我有一个非常简单的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
上下文。除此之外,没有任何配置可以阻止/启用期货的并行执行。
答案 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"
}