Scala 2.12 有 2Future.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)
}
重载版本返回最慢的版本。更准确地说,它只是从头到尾检查给定的列表,而不关心它们需要多长时间才能完成。
这是应该的吗?如果是这样,是否使用重复的或自己实施它只是关心他们完成时间的选择?