为什么ShutdownHookThread'setDaemon true'

编程入门 行业动态 更新时间:2024-10-25 09:36:39
本文介绍了为什么ShutdownHookThread'setDaemon true'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我最近需要向我拥有的Scala应用程序添加一个关闭挂钩,我发现Scala为此提供了一个名为 ShutdownHookThread .在其来源中,我注意到它将新线程设置为守护程序线程.

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.

两个部分:

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

  • 这源于对"Scala脚本"的要求(运行scala myfile.scala而不是先进行显式编译).讨论此处.现在已更改( commit ),因此赢得了ShutdownHookThread的未来版本没有此代码.
  • 我还没有发现任何决定性的东西,但是从实验上看,这并不重要.我认为这是有道理的,因为守护程序状态会影响JVM何时开始关闭,因此,在关闭程序进行之后,守护程序状态就没有关系了.
  • 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.
  • 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'

    本文发布于:2023-11-24 21:22:53,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1626885.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:ShutdownHookThread   true   setDaemon

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!