简体   繁体   English

Future.sequence 中使用的未来失败 - 报告哪个失败以及何时报告?

[英]A future used in Future.sequence fails - which failure is reported and when?

Multiple futures can be combined into one using Future.sequence .可以使用Future.sequence将多个期货组合成一个。 The result is obvious when all of them succeed - it is the sequence of the results, which is available once all of them have completed.当所有这些都成功时,结果是显而易见的——它是结果的顺序,一旦它们全部完成,就可以使用。 What is however not clear, and I did not find it documented, is what happens when some (perhaps even multiple) futures fail.然而,当一些(甚至多个)期货失败时会发生什么并不清楚,我也没有发现它记录在案。 My Scastie experiment seems to indicate that as soon as any future fails, the failure is reported immediately.我的Scastie 实验似乎表明,一旦任何未来失败,就会立即报告失败。

import scala.concurrent._
import scala.util._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration

val f1 = Future {
  Thread.sleep(600)
  println("f1 done")
}
val f2 = Future {
  Thread.sleep(400)
  println("f2 done")
  throw new Exception("Failed")
}
val f3 = Future {
  Thread.sleep(200)
  println("f3 done")
  throw new Exception("Failed")
}

val results = Future.sequence(Seq(f1, f2, f3))

results.onComplete {
  case Success(_) =>
    println("Seq completed")
  case Failure(_) =>
    println("Seq failed")
}

Await.result(results, Duration.Inf)

Gives result:给出结果:

f3 done f3 完成

Seq failed测序失败

Are there any guarantees or specification regarding which failure is reported and when once any of the futures fails?是否有关于报告哪个失败以及任何期货失败的时间的保证或规范?

Which future is returned is an implementation detail.返回哪个未来是一个实现细节。

The current implementation of Future.sequence in turn depends on the implementation of zipWith , which implementations of the Future trait are freely allowed to override, so it's not just a dependence on Future.sequence 's implementation but also on whatever library is giving you Future s (and things like Future.successful / Future.failed can behave differently from a Future { } or even a Future derived from something like a ZIO or a Cats-Effect IO or an Akka ask). Future.sequence的当前实现又依赖于zipWith的实现, Future trait 的实现可以自由覆盖,因此它不仅依赖于Future.sequence的实现,还依赖于任何库为您提供Future s (以及Future.successful / Future.failed类的行为可能与Future Future { }或什至源自ZIO或 Cats-Effect IO或 Akka 等问题的 Future 不同)。

In short, correctness should never depend on which failure is returned from Future.sequence : all you can depend on is that at least one of the futures failed.简而言之,正确性永远不应该取决于从Future.sequence返回哪个失败:您可以依赖的是至少有一个期货失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM