为什么Akka Streams应用程序没有正常终止?

时间:2017-09-12 04:05:50

标签: scala akka-stream alpakka

我使用Alpakka Cassandra Library

编写了这个简单的应用程序
package com.abhi

import akka.actor.ActorSystem
import akka.stream.{ActorMaterializer, ClosedShape}
import akka.stream.alpakka.cassandra.scaladsl.CassandraSource
import akka.stream.scaladsl.{Flow, GraphDSL, RunnableGraph, Sink}
import com.datastax.driver.core.{Cluster, Row, SimpleStatement}
import scala.concurrent.Await
import scala.concurrent.duration._

object MyApp extends App {
   implicit val actorSystem = ActorSystem()
   implicit val actorMaterializer = ActorMaterializer()
   implicit val session = Cluster
      .builder
      .addContactPoints(List("localhost") :_*)
      .withPort(9042)
      .withCredentials("foo", "bar")
      .build
      .connect("foobar")
   val stmt = new SimpleStatement("SELECT col1, col2 FROM foo").setFetchSize(20)
   val source = CassandraSource(stmt)
   val toFoo = Flow[Row].map(row => Foo(row.getLong(0), row.Long(1)))
   val sink = Sink.foreach[Foo](foo => println(foo.col1, foo.col2))
   val graph = RunnableGraph.fromGraph(GraphDSL.create(sink){ implicit b =>
      s =>
      import GraphDSL.Implicits._
      source.take(10) ~> toFoo ~> s
      ClosedShape
   })
   // let us run the graph
   val future = graph.run()
   import actorSystem.dispatcher
   future.onComplete{_ =>
      session.close()
      Await.result(actorSystem.terminate(), Duration.Inf)
   }
   Await.result(future, Duration.Inf)
   System.exit(0)
}

case class Foo(col1: Long, col2: Long)

此应用程序完全按预期运行,在屏幕上打印10行。

但发帖说它挂了。执行System.exit(0)调用时会抛出异常

Exception: sbt.TrapExitSecurityException thrown from the UncaughtExceptionHandler in thread "run-main-0"

但是应用程序仍然没有停止运行。它只是挂起。

我不明白为什么这个应用程序没有正常终止(实际上它甚至不需要system.exit(0)调用。

退出此应用程序的唯一方法是通过控件C。

1 个答案:

答案 0 :(得分:2)

这可能发生,因为sbt在自己的JVM实例中运行代码,然后System.exit将退出sbt的JVM,从而产生上述结果。

您是否尝试在您的sbt构建中的某处设置fork in run := true

我也不确定使用actorSystem.dispatcher执行你的onComplete回调是个好主意(因为你用它来等待actor系统本身的终止)。

你可以试试的东西:

import actorSystem.dispatcher
future.onComplete{ _ =>
  session.close()
  actorSystem.terminate()
}
Await.result(actorSystem.whenTerminated, Duration.Inf)

请注意,当剩下的唯一线程是守护程序线程时,JVM将退出而不需要调用System.exit(参见例如What is Daemon thread in Java?)。