Why does ShutdownHookThread 'setDaemon true'

耗尽温柔 提交于 2019-12-07 10:29:29

问题


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?


回答1:


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).




回答2:


Answering my own question here.

Two parts:

  1. Why does ShutdownHookThread make its new threads daemon=true?
  2. If a shutdown hook thread is daemon=true, what happens?

Answers:

  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.


来源:https://stackoverflow.com/questions/7768877/why-does-shutdownhookthread-setdaemon-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!