I'm currently writing codes to extend the Future companion object. One function I want to implement is
Any
//returns the future that computes the first value computed from the list. If the first one fails, fail.
def any[T](fs: List[Future[T]]): Future[T] = {
val p = Promise[T]()
fs foreach { f => {
f onComplete {
case Success(v) => p trySuccess v
case Failure(e) => p tryFailure e
}
} }
p.future
}
test("A list of Futures return only the first computed value") {
val nums = (0 until 10).toList
val futures =
nums map { n => Future { Thread.sleep(n*1000); n } }
val v = Await.result(Future.any(futures), Duration.Inf)
assert(v === 0)
}
n*1000
(n+1)*1000
Thread.sleep
is a blocking operation in your Future
but you are not signaling to the ExecutionContext
that you are doing so, so the behavior will vary depending on what ExecutionContext you use and how many processors your machine has. Your code works as expected with ExecutionContext.global
if you add blocking
:
nums map { n => Future { blocking { Thread.sleep(n*1000); n } } }