为什么ShutdownHookThread“setDaemon true”
我最近需要向我拥有的 Scala 应用程序添加一个关闭钩子,我发现 Scala 为此提供了一个帮助程序 ShutdownHookThread。在其源代码中,我注意到 它将新线程设置为守护线程。
def apply(body: => Unit): ShutdownHookThread = {
val t = new ShutdownHookThread(hookName()) {
override def run() = body
}
t setDaemon true // <--------- right here
runtime addShutdownHook t
t
}
为什么要这样做?在我看来,您可能希望在关闭钩子线程中执行相反的操作(即确保该线程在关闭 jvm 之前退出)。或者守护进程/非守护进程与关闭挂钩不相关吗?
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
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 JVM 上,通常非守护线程会阻止 JVM 终止。一旦不再有任何非守护线程,JVM 将通过启动关闭来正常终止。请参阅 addShutdownHook javadoc 了解更多信息。
一旦启动关闭,我不确定守护进程状态是否重要。此外,在启动关闭之前,不会启动关闭挂钩线程。因此,在这种情况下,
t setDaemon true
可能是不必要的,但也没有什么坏处。简而言之,“守护进程”语义与 unix 不同(在 unix 领域,它表示持续运行的线程)。
On the JVM, in general a non-daemon thread will prevent the JVM from terminating. Once there are no longer any non-daemon threads, then the JVM will gracefully terminate by initiating shutdown. See the addShutdownHook javadoc for more info.
Once shutdown has been initiated, I'm not sure daemon status matters. Also shutdown hook threads aren't started until the shutdown has been initiated. So in this case
t setDaemon true
may be unnecessary, but it won't hurt either.So in short the "daemon" semantic differs from unix (where in unix land it denotes a thread that keeps running).
在这里回答我自己的问题。
两个部分:
ShutdownHookThread
使其新线程 daemon=true?答案:
ShutdownHookThread 的未来版本
不会有此代码。Answering my own question here.
Two parts:
ShutdownHookThread
make its new threads daemon=true?Answers:
scala myfile.scala
rather than explicitly compiling first). Discussion here. It has now been changed (commit), so future versions ofShutdownHookThread
won't have this code.