В 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)
}
Перегруженная версия возвращает самую медленную. Чтобы быть более точным, он просто проверяет заданный список от начала до конца, и ему все равно, сколько времени потребуется для их завершения.
Это как должно быть? Если да, то использует ли дублированный или реализует его сам единственный вариант, чтобы заботиться о том, чтобы их время было завершено?
a
являетсяiterator
; он будет использованval c = Future.firstCompletedOf(a)
, аval b = Future.find(a)(_.isInstanceOf[Int])
получит пустойiterator
. - person sarveshseri   schedule 13.12.2018