Scala Futures do not work in parallel

I have a very simple Maven spring MVC project and I added Scala to it. I want the next three futures to execute at the same time, as intended. However, they are executed one by one.

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 use the scala.concurrent.ExecutionContext.Implicits.global context. In addition, there is no configuration that can prevent / enable parallel execution of futures.

+6
source share
1 answer

For understanding, only syntactic sugar is used and translated to flatMap, as in example 2 .

This means that your code will look something like this:

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

As you can see, Future only starts after the previous completion. To get around this, first run your Future , and then do this for understanding:

 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" } 
+8
source

Source: https://habr.com/ru/post/978920/


All Articles