簡體   English   中英

Scala Futures沒有並行運行

[英]Scala Futures not running in parallel

我有一個非常簡單的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上下文。 除此之外,沒有可以阻止/啟用期貨並行執行的配置。

因為理解只是語法糖,並且像示例2一樣轉換為flatMap

這意味着您的代碼大致如下所示:

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

如您所見, Future s僅在上一次完成之后啟動。 為了解決這個問題,首先啟動你的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"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM