4

What happens to dangling threads in Java?

Like if I create an application and it spawns multiple threads. And one of the threads does not finish and the main program finishes before that. What will happen to this dangling thread? Will it stay in the thread pool infinitely or JVM will kill the thread after a threshold time period???

divinedragon
  • 5,105
  • 13
  • 50
  • 97
  • Related to: http://stackoverflow.com/questions/2213340/what-is-daemon-thread-in-java – Gray Apr 05 '12 at 13:03

1 Answers1

9

It depends on if the thread has been marked as "daemon" or not. Daemon threads will be killed when the JVM exits. If there are any threads that are not daemon then the JVM will not exit at all. It will wait for those threads to finish first.

By default, threads take the daemon status of their parent thread. The main thread has daemon set false so any threads forked by it will also be false. You can set the daemon flag to true before the thread starts with this:

Thread thread = new Thread(...);
thread.setDaemon(true);
thread.start();
Gray
  • 115,027
  • 24
  • 293
  • 354
  • +1, and perhaps another one if you can explain or suggest why the default setting is 'prevent apps from closing down'. If the language/runtime developers wanted to really stuff up developers, they could have added a default 'refuse to start up' feature as well :(( – Martin James Apr 05 '12 at 13:58
  • @Martin I think they made the decision that threads are non-daemon so the JVM wouldn't just kill them when main finished. If they were kill-able, you'd have to say so explicitly. I think they made the right choice myself. – Gray Apr 05 '12 at 14:01
  • Thanks guys for the insight. How can I apply the same for Callable threads then? – divinedragon Apr 05 '12 at 14:32
  • You mean in an `Executor`? You need to use a `ThreadFactory` that creates non-daemon threads. See here: http://stackoverflow.com/a/1517264/179850 – Gray Apr 05 '12 at 14:36
  • Can you provide insights at this question [here](http://stackoverflow.com/questions/10030808/making-callable-threads-as-daemon) – divinedragon Apr 05 '12 at 14:46
  • The main method cannot exit till any of the user thread is still running. Means there can't be any dangling non-daemon thread after the main method exits. More explanation is in this thread. http://stackoverflow.com/questions/9651842/will-main-thread-exit-before-child-threads-complete-execution – dharam Apr 05 '12 at 15:02
  • Till any of the non-daemon threads are still running, @dharam. "user" threads is a bit of a misnomer. – Gray Apr 05 '12 at 15:16
  • *By default, threads are not daemon threads* - The thread inherits the parent's daemon flag. Note the parent thread is the thread calling the c-tor. Thread created by clone() has the cloned daemon status. Only the very first thread created by the JVM has default daemon status (false) - the rest do not. – bestsss Jul 02 '12 at 12:43
  • Good post @bestss. I've tuned by answer. THanks. – Gray Jul 02 '12 at 13:27