Scala:如果我们不知道未来的执行时间,如何关闭执行程序?

Scala: How to shutdown executor if we don't know the execution time in future?

假设我有一个简单的应用程序

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 分钟等

我怎样才能做到这一点?

在你的简单案例中:

Future.sequence(....).onComplete{_ => executionContext.shutdownNow()}

但是如果您有许多循环相关计算并且您需要知道它们何时完成 - 您可以使用格抽象。它出现在@philippkhaller 的“Programming with Futures, Lattices, and Quiescence”中。