gpt4 book ai didi

scala - future /成功竞赛

转载 作者:行者123 更新时间:2023-12-04 14:45:44 24 4
gpt4 key购买 nike

我正在学习 future ,我正在尝试创建一种方法,将两个 future 作为参数
( fg )并返回第一个成功完成的 future ,否则返回 fg .

一些用于说明我的方法行为的用例是:

Future 1        | Future 2         | Result
Success First Success Second Future 1
Success First Failure Second Future 1
Success Second Success First Future 2
Success Second Failure First Future 1
Failure First Failure Second Future 2 (because we had a failure on Future 1, so try to see what is the result Future 2)

所以我创建了这个方法:
def successRace(f: Future[T], g: Future[T]): Future[T] = {
val p1 = Promise[T]()
val p2 = Promise[T]()
val p3 = Promise[T]()
p1.completeWith(f)
p2.completeWith(g)
p3. ????
p3.future
}

现在,我怎么知道哪个先完成了?

最佳答案

用例是第一次成功完成:

scala> :pa
// Entering paste mode (ctrl-D to finish)

def firstSuccessOf[T](fs: Future[T]*)(implicit x: ExecutionContext): Future[T] = {
val p = Promise[T]()
val count = new java.util.concurrent.atomic.AtomicInteger(fs.size)
def bad() = if (count.decrementAndGet == 0) { p tryComplete new Failure(new RuntimeException("All bad")) }
val completeFirst: Try[T] => Unit = p tryComplete _
fs foreach { _ onComplete { case v @ Success(_) => completeFirst(v) case _ => bad() }}
p.future
}

// Exiting paste mode, now interpreting.

firstSuccessOf: [T](fs: scala.concurrent.Future[T]*)(implicit x: scala.concurrent.ExecutionContext)scala.concurrent.Future[T]

所以
scala> def f = Future { Thread sleep 5000L ; println("Failing") ; throw new NullPointerException }
f: scala.concurrent.Future[Nothing]

scala> def g = Future { Thread sleep 10000L ; println("OK") ; 7 }
g: scala.concurrent.Future[Int]

scala> firstSuccessOf(f,g)
res3: scala.concurrent.Future[Int] = scala.concurrent.impl.Promise$DefaultPromise@5ed53f6b

scala> res0Failing
3.value
res4: Option[scala.util.Try[Int]] = None

scala> res3.valueOK

res5: Option[scala.util.Try[Int]] = Some(Success(7))

或者
scala> def h = Future { Thread sleep 7000L ; println("Failing too") ; throw new NullPointerException }
h: scala.concurrent.Future[Nothing]


scala> firstSuccessOf(f,h)
res10: scala.concurrent.Future[Nothing] = scala.concurrent.impl.Promise$DefaultPromise@318d30be

scala>

scala> res10.Failing
value
res11: Option[scala.util.Try[Nothing]] = None

scala> Failing too


scala> res10.value
res12: Option[scala.util.Try[Nothing]] = Some(Failure(java.lang.RuntimeException: All bad))

@ ysusuk 的回答是什么 Future.firstCompletedOf在引擎盖下。

关于scala - future /成功竞赛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20659406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com