Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dangling Threads in Java

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???

like image 849
divinedragon Avatar asked Jan 18 '23 00:01

divinedragon


1 Answers

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();
like image 144
Gray Avatar answered Jan 30 '23 22:01

Gray