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???
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With