複数の先物を並行して実行する必要があり、プログラムがクラッシュまたはハングすることはありません。
今のところ、future を 1 つずつ待ち、TimeoutException が発生した場合はフォールバック値を使用します。
val future1 = // start future1
val future2 = // start future2
val future3 = // start future3
// <- at this point all 3 futures are running
// waits for maximum of timeout1 seconds
val res1 = toFallback(future1, timeout1, Map[String, Int]())
// .. timeout2 seconds
val res2 = toFallback(future2, timeout2, List[Int]())
// ... timeout3 seconds
val res3 = toFallback(future3, timeout3, Map[String, BigInt]())
def toFallback[T](f: Future[T], to: Int, default: T) = {
Try(Await.result(f, to seconds))
.recover { case to: TimeoutException => default }
}
ご覧のとおり、このスニペットの最大待機時間はtimeout1 + timeout2 + timeout3
私の質問は次のとおりです。これらの先物すべてを一度に待機して、待機時間を に短縮するにはどうすればよいmax(timeout1, timeout2, timeout3)
ですか?
編集:最後に、@Jatin と @senia の回答の変更を使用しました:
private def composeWaitingFuture[T](fut: Future[T],
timeout: Int, default: T) =
future { Await.result(fut, timeout seconds) } recover {
case e: Exception => default
}
その後、次のように使用されます。
// starts futures immediately and waits for maximum of timeoutX seconds
val res1 = composeWaitingFuture(future1, timeout1, Map[String, Int]())
val res2 = composeWaitingFuture(future2, timeout2, List[Int]())
val res3 = composeWaitingFuture(future3, timeout3, Map[String, BigInt]())
// takes the maximum of max(timeout1, timeout2, timeout3) to complete
val combinedFuture =
for {
r1 <- res1
r2 <- res2
r3 <- res3
} yield (r1, r2, r3)
後で、必要に応じて使用combinedFuture
します。