【发布时间】:2017-05-13 21:25:00
【问题描述】:
根据 Scala 文档,不应在 Future 上进行阻塞。
“如前所述,为了性能和防止死锁,强烈建议不要对 future 进行阻塞。future 上的回调和组合器是使用其结果的首选方式。但是,在某些情况下可能需要阻塞并且受 Futures 和 Promises API 的支持。”
在我的程序退出之前,如何确保我的所有 Futures 都已完成(并且它们的回调已完成)?我通常在 main 函数的末尾使用 Await.result 来确保所有 Futures 都已完成。
object ConcurrencyExample extends App {
val gpf= Future {some operations}
val ccf = Future{some operations}
val atbf = for {g <- gpf
c <- ccf if c == true} yield {some operations}
//is it OK to use Await? If not, how do I ensure that all Futures have finished
?
Await.result(atbf,1000 millis )
}
问题
- 使用 Await 是否错误?否则我的代码不会等待 Futures 完成
- 如果是这样,有什么替代方案?
- 如何确保 Future 及其回调在我的主程序退出之前完成?
【问题讨论】:
标签: scala