简体   繁体   English

Scala的未来firstcompletedof超时

[英]timeout in scala's future firstcompletedof

I think I have a problem understanding firstCompletedOf. 我认为我在理解firstCompletedOf时遇到问题。 Given a completing future and a non completing future, I get a timeout when running the following for four times. 给定一个完整的未来和一个不完整的未来,我在运行以下命令四次时会超时。

Given this method f: 给定此方法f:

def f = {
  val completingFuture = Future {
    1
  }
  val nonCompletingFuture = Future {
    while (true) {}
  }
  val combinedFuture = Future.firstCompletedOf(List(
   completingFuture,
    nonCompletingFuture
  ))
  val result = Await.result(combinedFuture, 10.seconds)
  println(result)
}


f
f
f
f

When I run it four times as shown above, I get a timed out exception. 当我如上所述运行四次时,出现超时异常。 So I thought there cannot be such an exception because the completing future always returns. 所以我认为不可能有这样的例外,因为完整的未来总会回来。

The exception is 例外是

Exception in thread "main" java.util.concurrent.TimeoutException: Futures timed out after [10 seconds] 线程“主”中的异常java.util.concurrent.TimeoutException:期货在[10秒]后超时

Where am I mistaken? 我在哪里弄错了?

Your task while (true) {} never completes. while (true) {}您的任务永远不会完成。 It blocks a thread in an execution context forever. 它永远在执行上下文中阻塞线程。 So every time you run f , you lose one thread in the execution context until it runs out of threads and you start receiving timeouts. 因此,每次运行f ,您都会在执行上下文中丢失一个线程,直到该线程用完线程并开始接收超时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM