为什么ShutdownHookThread'setDaemon true' [英] Why does ShutdownHookThread 'setDaemon true'

查看:131
本文介绍了为什么ShutdownHookThread'setDaemon true'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近需要向我拥有的Scala应用程序添加一个关闭挂钩,我发现Scala为此提供了一个名为

I recently needed to add a shutdown hook to a Scala app I have, and I discovered that Scala provides a helper for this called ShutdownHookThread. In its source I noticed that it sets the new thread to be a daemon thread.

def apply(body: => Unit): ShutdownHookThread = {
  val t = new ShutdownHookThread(hookName()) {
    override def run() = body
  }
  t setDaemon true  // <--------- right here
  runtime addShutdownHook t
  t
}

为什么要这样做?在我看来,您可能想在shutdown钩子线程中使用相反的方法(即,在关闭jvm之前确保该线程退出).还是守护程序/非守护程序与关闭挂钩无关?

Why is this done? It seems to me you'd probably want the opposite in a shutdown hook thread (i.e. make sure that thread exits before shutting down the jvm). Or is daemon/not-daemon not relevant for shutdown hooks?

推荐答案

在这里回答我自己的问题.

Answering my own question here.

两个部分:

  1. 为什么ShutdownHookThread使其新线程daemon = true?
  2. 如果关闭挂钩线程是daemon = true,会发生什么情况?
  1. Why does ShutdownHookThread make its new threads daemon=true?
  2. If a shutdown hook thread is daemon=true, what happens?

答案:

  1. 这源于对"Scala脚本"的要求(运行scala myfile.scala而不是先进行显式编译).讨论此处.现在已更改( commit ),因此赢得了ShutdownHookThread的未来版本没有此代码.
  2. 我还没有发现任何决定性的东西,但是从实验上看,这并不重要.我认为这是有道理的,因为守护程序状态会影响JVM何时开始关闭,因此,在关闭程序进行之后,守护程序状态就没有关系了.
  1. This stemmed from requirements for "Scala scripting" (running scala myfile.scala rather than explicitly compiling first). Discussion here. It has now been changed (commit), so future versions of ShutdownHookThread won't have this code.
  2. I haven't found anything decisive, but experimentally it seems not to matter. I think this makes sense since daemon status affects when the JVM will commence shutdown, so after shutdown's already underway, daemon status shouldn't matter.

这篇关于为什么ShutdownHookThread'setDaemon true'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆