假设我有一个简单的应用程序
object FutureApp extends App {
val executor = newFixedThreadPool(8)
implicit val executionContext = fromExecutorService(executor)
val start = currentTimeMillis()
/*
* In real application we don't know how long it could take to execute the
* future body
*/
val f0: Future[Int] = Future { Thread.sleep(2700); 0 }
val f1: Future[Int] = Future { Thread.sleep(5500); 1 }
val f2: Future[Int] = Future { Thread.sleep(1500); 2 }
val seq: Future[List[Int]] = Future.sequence(f0 :: f1 :: f2 :: Nil)
seq onComplete {
case Success(res) => println { "R:" + res }
case Failure(t) => println { "R:" + t.getMessage }
}
/*
* Instead of invoking the code below I want to shutdown the
* executor without specifying the biggest execution time (5500)
*/
if (!executionContext.awaitTermination(5500, MILLISECONDS)) {
val end = currentTimeMillis()
println { s"executionTime=${(end - start).toDouble / 1000}" }
executionContext.shutdownNow()
}
}
它在未来的三个实体(body: =>T
)中执行代码。我想结合期货执行的结果,为此,我使用Future.sequence
函数。我只需要解决一个问题。我需要关闭最大执行时间的执行程序,我不知道。它可能是5秒或10分钟等等。
我怎样才能做到这一点?
答案 0 :(得分:3)
在你的简单案例中:
但是如果你有许多循环依赖计算,你需要知道它们何时完成 - 你可以使用格抽象。它出现在" Programming with Futures, Lattices, and Quiescence" @philippkhaller撰写。