【问题标题】:The Future is not complete?未来不完整?
【发布时间】:2015-11-01 06:04:41
【问题描述】:
object Executor extends App {
  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()
  implicit val ec = system.dispatcher
  import akka.stream.io._
  val file = new File("res/AdviceAnimals.tsv")
  import akka.stream.io.Implicits._
  val foreach: Future[Long] = SynchronousFileSource(file)
    .to( Sink.outputStream(()=>System.out))
    .run()

  foreach onComplete { v =>
    println(s"the foreach is ${v.get}")  // the will not be print
  }
}

但如果我将Sink.outputStream(()=>System.out) 更改为Sink.ignoreprintln(s"the foreach is ${v.get}") 将打印出来。

谁能解释一下原因?

【问题讨论】:

  • 从字符串中提取表达式。 val vGet = v.get; println(s"the foreach is $vGet") -- 那会发生什么?
  • 我试过了,没有成功,我猜Sink.outputStream(()=>System.out)已经被屏蔽了。但我不知道为什么?
  • “不成功”是什么意思?症状是什么?您是否仍然收到“未来不完整”的消息? O/w 你有一个不同的问题。我强烈怀疑您必须阅读有关 onComplete 的参数的文档。

标签: scala stream future


【解决方案1】:

您不是在等待流完成,而是您的 main 方法(Executor 的主体)将完成,并且由于 main 方法完成退出,JVM 被关闭。

您想要做的是阻止该线程并且在未来完成之前不退出应用程序。

object Executor extends App {
  // ...your stuff with streams...
  val yourFuture: Future[Long] = ???

  val result = Await.result(yourFuture, 5 seconds)
  println(s"the foreach is ${result}")

  // stop the actor system (or it will keep the app alive)
  system.terminate()
}

【讨论】:

  • 嗯,这并不完全正确,因为应用程序在 ActorSystem 关闭之前不会退出。
【解决方案2】:

巧合的是,我创建了几乎相同的应用程序来测试/玩 Akka Streams。 导入的隐式会导致问题吗? 这个应用对我来说很好用:

object PrintAllInFile extends App {
  val file = new java.io.File("data.txt")

  implicit val system = ActorSystem("test")
  implicit val mat    = ActorMaterializer()
  implicit val ec     = system.dispatcher

  SynchronousFileSource(file)
    .to(Sink.outputStream(() => System.out))
    .run()
    .onComplete(_ => system.shutdown())
}

注意“onComplete”中 ActorSystem 的停止。否则应用程序不会退出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    相关资源
    最近更新 更多