gpt4 book ai didi

Scala Future.find

转载 作者:行者123 更新时间:2023-12-01 04:31:34 24 4
gpt4 key购买 nike

Scala 2.12 有 2 Future.find方法。

@deprecated("use the overloaded version of this method that takes a scala.collection.immutable.Iterable instead", "2.12.0")
def find[T](@deprecatedName('futurestravonce) futures: TraversableOnce[Future[T]])(@deprecatedName('predicate) p: T => Boolean)(implicit executor: ExecutionContext): Future[Option[T]]

以及它的重载版本
def find[T](futures: scala.collection.immutable.Iterable[Future[T]])(p: T => Boolean)(implicit executor: ExecutionContext): Future[Option[T]]

两者都有相同的描述

  /** Asynchronously and non-blockingly returns a `Future` that will hold the optional result
* of the first `Future` with a result that matches the predicate, failed `Future`s will be ignored.
*
* @tparam T the type of the value in the future
* @param futures the `scala.collection.immutable.Iterable` of Futures to search
* @param p the predicate which indicates if it's a match
* @return the `Future` holding the optional result of the search
*/


所以我假设这些方法首先找到完成 Future匹配参数 p在给定的列表中

但只有第一个真正这样做了。
  val start = System.currentTimeMillis
val a = (1 to 3).reverse.iterator.map{ x =>
Future{
Thread.sleep(x * 10000)
x
}
}
val b = Future.find(a)(_.isInstanceOf[Int])
b.foreach{ x =>
println(x)
println(System.currentTimeMillis - start) // 10020
}

该方法的弃用版本返回最快的版本。
  val a = (1 to 3).reverse.map{ x =>
Future{
Thread.sleep(x * 10000)
x
}
}
val b = Future.find(a)(_.isInstanceOf[Int])
b.foreach{ x =>
println(x)
println(System.currentTimeMillis - start)
}

重载版本返回最慢的版本。更准确地说,它只是从头到尾检查给定的列表,并不关心完成它们需要多长时间。

这是应该的样子吗?如果是这样,是使用重复的还是自己实现它的唯一选择来关心他们完成的时间?

最佳答案

您是对的 deprecated Future.find期望 TraversableOnce[Future[T]]在 2.12.x 中的行为与替换 Future.find 的行为不同.从下面粘贴的源代码可以看出,前者find方法利用 PromisetryComplete从输入集合中有效地捕获第一个完整的 future ,而后者使用一个简单的 hasNext/next遍历:

@deprecated("use the overloaded version of this method that takes a scala.collection.immutable.Iterable instead", "2.12.0")
def find[T](@deprecatedName('futurestravonce) futures: TraversableOnce[Future[T]])(@deprecatedName('predicate) p: T => Boolean)(implicit executor: ExecutionContext): Future[Option[T]] = {
val futuresBuffer = futures.toBuffer
if (futuresBuffer.isEmpty) successful[Option[T]](None)
else {
val result = Promise[Option[T]]()
val ref = new AtomicInteger(futuresBuffer.size)
val search: Try[T] => Unit = v => try {
v match {
case Success(r) if p(r) => result tryComplete Success(Some(r))
case _ =>
}
} finally {
if (ref.decrementAndGet == 0) {
result tryComplete Success(None)
}
}

futuresBuffer.foreach(_ onComplete search)

result.future
}
}

def find[T](futures: scala.collection.immutable.Iterable[Future[T]])(p: T => Boolean)(implicit executor: ExecutionContext): Future[Option[T]] = {
def searchNext(i: Iterator[Future[T]]): Future[Option[T]] =
if (!i.hasNext) successful[Option[T]](None)
else {
i.next().transformWith {
case Success(r) if p(r) => successful(Some(r))
case other => searchNext(i)
}
}
searchNext(futures.iterator)
}

实现自己的一种方法可能是扩展 Future.firstCompletedOf添加谓词的方法如下所示:
def firstConditionallyCompletedOf[T](futures: List[Future[T]])(p: T => Boolean)(implicit ec: ExecutionContext): Future[T] = {
val p = Promise[T]()
val firstCompleteHandler = new AtomicReference[Promise[T]](p) with (Try[T] => Unit) {
override def apply(v1: Try[T]): Unit = getAndSet(null) match {
case null => ()
case some => some tryComplete v1
}
}
futures.foreach{ _.filter(condition).onComplete(firstCompleteHandler) }
p.future
}

关于Scala Future.find,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53759765/

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