【问题标题】:Scala App doesn't exit even though Future is completed即使 Future 完成,Scala App 也不会退出
【发布时间】:2023-04-04 00:30:01
【问题描述】:

我等待 Future 完成并在控制台上打印内容。即使一切都完成了,主应用程序也不会退出,我必须手动杀死它。

def main(args: Array[String]): Unit {
    val req = HttpRequest(GET, myURL)
    val res = Http().singleRequest(req)
    val resultsFutures = Future {
        val resultString = Await.result(HttpRequests.unpackResponse(res), Duration.Inf)
        JsonMethods.parse(resultString).extract[List[Results]]
    }
    val results = Await.result(resultsFutures, Duration.Inf)
    println(results)
}

所以results 在控制台上打印出预期的竞争,但应用程序仍然没有结束。 我可以做些什么来退出应用程序吗?是否还有一些东西正在运行,主要在等待?

我正在使用:

  • scala 2.12.10
  • akka 2.5.26
  • akkaHttp 10.1.11

【问题讨论】:

    标签: scala akka akka-http concurrent.futures


    【解决方案1】:

    当您使用 Akka 时,您可能会在后台以某种方式实例化 ActorSystem,以保持进程运行。

    您可以亲自动手并调用它的actorSystem.terminate() 方法,或者您也可以在main 方法的末尾使用显式的sys.exit(0)0 是您想要的退出代码)。

    编辑:您还应该将Awaits 包装在Try 中,并确保在发生故障时也调用sys.exit

    【讨论】:

    • 是的,我在运行 main 的对象中有一个 implicit val system: ActorSystem = ActorSystem()
    • 将其更改为显式 val system: ActorSystem = ActorSystem()。然后我打电话给system.terminate()(不推荐使用.shutdown),但这仍然没有结束应用程序。除了调用sys.exit(0) 之外,还有其他方法吗?因为这似乎是蛮力的,应该有一个预期的方法?
    • 我的错误,必须捕获所有函数中的所有隐式 ActorSystems 并在它们完成工作后终止它们。干得好,这是正确的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多