我有一个非常简单的Maven spring MVC项目,我添加了Scala.我希望以下三个期货能够按预期同时执行.然而,他们一个接一个地执行
val viewName: Future[String] = for {
profileSync <- Future { EmployeeLocalServiceUtil.syncProfileInformation() }
earningsSync <- Future { EmployeeLocalServiceUtil.syncEarnings() }
reimbursementSync <- Future { EmployeeLocalServiceUtil.syncReimbursements() }
} yield {
"employee/view"
}
Run Code Online (Sandbox Code Playgroud)
我的机器有4个核心,我正在使用scala.concurrent.ExecutionContext.Implicits.global上下文.除此之外,没有可以阻止/启用期货并行执行的配置.
因为理解只是语法糖,并且像示例2一样被转换为flatMap.
这意味着您的代码大致如下所示:
Future { ??? }.flatMap { profileSync =>
Future { ??? }.flatMap { earningsSync =>
Future { ??? }.map { reimbursementSync =>
// Able to access profileSync/earningsSync/reimbursementSync values.
"employee/view"
}
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,Futures仅在上一次完成后才启动.为了解决这个问题,首先启动你的Futures然后进行理解:
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"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
376 次 |
| 最近记录: |