从官方教程参考中,我不能完全理解未来的一个方面。http://docs.scala-lang.org/overviews/core/futures.html
scala中的期货是否有某种内置的超时机制?假设下面的例子是一个5‘s的文本文件..."Implicits.global“的隐含作用域最终会导致onFailure以非阻塞方式触发吗?还是可以定义?如果没有某种类型的默认超时,这是否意味着成功或失败都不会触发?
import scala.concurrent._
import ExecutionContext.Implicits.global
val firstOccurence: Future[Int] = future {
val source = scala.io.Source.fromFile("myText.txt")
source.toSeq.indexOfSlice("myKeyword")
}
firstOccurence onSuccess {
case idx => println("The keyword first appears at position: " + idx)
}
firstOccurence onFailure {
case t => println("Could not process file: " + t.getMessage)
}发布于 2017-02-26 20:17:31
如果您希望写入者(promise holder)是控制超时逻辑的人,请按以下方式使用akka.pattern.after:
val timeout = akka.pattern.after(10 seconds, system.scheduler)(Future.failed(new TimeoutException(s"timed out during...")))
Future.firstCompletedOf(Seq(promiseRef.future, timeout))这样,即使您的promise completed逻辑从未发生,您的调用者的未来仍将在某个时候以失败告终。
https://stackoverflow.com/questions/16304471
复制相似问题