I have a very simple Maven spring MVC project and I added Scala to it. I want the following three futures to execute concurrently as they are supposed to. However they execute one after the other
val viewName: Future[String] = for {
profileSync <- Future { EmployeeLocalServiceUtil.syncProfileInformation() }
earningsSync <- Future { EmployeeLocalServiceUtil.syncEarnings() }
reimbursementSync <- Future { EmployeeLocalServiceUtil.syncReimbursements() }
} yield {
"employee/view"
}
My machine has 4 cores and I am using scala.concurrent.ExecutionContext.Implicits.global
context. Apart from this there is no configuration which can prevent/enable parallel execution of the futures.
For comprehensions are only syntactic sugar and are translated to flatMap like in Example 2.
Which means your code will roughly look like this:
Future { ??? }.flatMap { profileSync =>
Future { ??? }.flatMap { earningsSync =>
Future { ??? }.map { reimbursementSync =>
// Able to access profileSync/earningsSync/reimbursementSync values.
"employee/view"
}
}
}
As you see Future
s are only being launched after the previous completed. To get around this first start your Future
s and then do the for comprehension:
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With