【问题标题】:future take a long time to run, why not return immediately?未来需要很长时间才能运行,为什么不立即返回?
【发布时间】:2014-04-23 20:51:38
【问题描述】:

我有以下代码,我希望 a.success(burncpu(14969)) 会立即返回,因为它会在未来运行,但为什么它需要很长时间才能运行。

import scala.concurrent._
val a=Promise[Unit]()
// why the following took long time here, shouldn't it be in async mode, and return very quick
a.success(burncpu(14969))  
a.future


def burncpu(a:Int):Int = {
  val point=new Date().getTime()
  while ((new Date()).getTime()-point< a) {
    a
  }
  a
}        

【问题讨论】:

    标签: scala future


    【解决方案1】:

    你使用Promise错了。

    a.success 方法使用给定参数完成承诺,它不会异步运行您传递给它的表达式。

    你可能想做的是这样的:

    val f = Future(burncpu(6000))
    

    假设您有一个可用的ExecutionContext(如果没有,您可以使用import ExecutionContext.Implicits.global),这将构造一个Future,它将异步运行您的函数。

    您可以在 Scala REPL 中查看它是如何工作的(f.value 返回 None,直到方法返回)

    scala> val f = Future(burncpu(6000))
    f: scala.concurrent.Future[Int] = scala.concurrent.impl.Promise$DefaultPromise@4d4d8fcf
    
    scala> f.value
    res27: Option[scala.util.Try[Int]] = None
    
    scala> f.value
    res28: Option[scala.util.Try[Int]] = None
    
    scala> f.value
    res29: Option[scala.util.Try[Int]] = Some(Success(6000))
    

    【讨论】:

      【解决方案2】:

      Promise.success不是异步执行的,基本上你的代码相当于:

      Future.successful(burncpu(14969))
      

      你可以试试这个:

      Future {
        burncpu(14969)
      }
      

      这将调用Future.apply 并异步执行您的函数。

      【讨论】:

        【解决方案3】:

        future 的调用确实是异步调用的。 但是,API 中没有任何内容表明完成Promise,即在您的情况下调用success,将异步执行。这是您确保的责任。

        当您考虑 Promise 是什么 - 另一个执行路径的“标记”,通知它计算已完成并且结果(或失败)可用时,这是有道理的。

        【讨论】:

          猜你喜欢
          • 2020-11-08
          • 2015-11-12
          • 2014-07-21
          • 1970-01-01
          • 1970-01-01
          • 2013-10-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多