Hanging themes in Java

What happens to dangling threads in Java?

It's like I am creating an application and it spawns multiple threads. And one of the threads does not end, and the main program ends before that. What will happen to this dangling thread? Will it stay in the thread pool indefinitely or will the JVM kill the thread after a threshold period of time?

+3


source to share


1 answer


It depends on whether the thread has been marked as "daemon" or not. The daemon threads will be killed when the JVM exits. If there are any threads that are not daemons then the JVM will not exit at all. It will wait for these threads to complete.

By default, threads assume the daemon status of their parent thread. The main thread has a daemon set false

, so any threads it spawns will also false

. You can set the daemon flag true

before the thread starts with this:



Thread thread = new Thread(...);
thread.setDaemon(true);
thread.start();

      

+9


source







All Articles