Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Futures not running in parallel

Tags:

scala

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.

like image 630
Robin Avatar asked Dec 01 '14 03:12

Robin


1 Answers

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 Futures are only being launched after the previous completed. To get around this first start your Futures 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"
}
like image 157
Akos Krivachy Avatar answered Sep 21 '22 11:09

Akos Krivachy