从未完成的未来

アレッ*_*ックス 7 concurrency scala future

需要测试一些可能导致超时的方法,我想为此创建一个辅助函数.它应该返回一个Future从来没有完成:

def neverCompletes[T]: Future[T] = { ... }
Run Code Online (Sandbox Code Playgroud)

但我想知道,我怎么能这样做?我可能喜欢以下内容:

def neverCompletes[T]: Future[T] = {
  val p = Promise[T]()
  future {
    while(true) { }
  } onComplete {
    case x => 
      p complete x // needed?
      println("something went wrong!!!") // something is wrong...
  }

  p.future
}
Run Code Online (Sandbox Code Playgroud)

但应该有更好的方法来实现这一目标.我也不确定p complete x // needed?那里是否需要.

dre*_*xin 24

更新:

在Scala 2.12中,将有一个Future.never返回永不完成的未来的方法.


简单的事情.只需创建一个Promise并返回它,Future而不是完成它:

def neverCompletes[T]: Future[T] = Promise[T].future
Run Code Online (Sandbox Code Playgroud)

  • 不,未来总是有承诺作为对手.实际上它甚至是同一个对象:https://github.com/scala/scala/blob/master/src/library/scala/concurrent/impl/Promise.scala#L21 (2认同)