Just like threads, Thread groups can also be daemon and non daemon. Daemon thread group does not mean that it will have all daemon threads in it.
A daemon thread group is a threadgroup that is automatically destroyed when its last thread is stopped or its last thread group is destroyed.
A non daemon thread group is not destroyed automatically even if there are no active threads in it or no child thread groups.
Consider this code :
We will be creating the following hierarchy of thread groups and each thread group will have the mentioned threads in it.
Main Threadgroup - 2 threads: one main , one thread-1
|
child Threadgroup - 1 thread: thread-2
|
child child Threadgroup - 1 thread: thread-3
|
child child child Threadgroup (daemon thread group) - 1 thread : thread-4
Code:
class CustomRunnable implements Runnable {
@Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(Thread.currentThread().getThreadGroup(), new CustomRunnable(), "Thread-1");
ThreadGroup childOfMainThreadGroup = new ThreadGroup("childOfMainThreadGroup");
Thread t2 = new Thread(childOfMainThreadGroup, new CustomRunnable(), "Thread-2");
ThreadGroup childChildOfMainThreadGroup = new ThreadGroup(childOfMainThreadGroup, "childChildOfMainThreadGroup");
Thread t3 = new Thread(childChildOfMainThreadGroup, new CustomRunnable(), "Thread-3");
// We will create a daemon thread group
ThreadGroup childChildChildOfMainThreadGroup = new ThreadGroup(childChildOfMainThreadGroup, "childChildChildOfMainThreadGroup");
childChildChildOfMainThreadGroup.setDaemon(true);
// This is non daemon thread in it
Thread t4 = new Thread(childChildChildOfMainThreadGroup, new CustomRunnable(), "Thread-4");
t1.start();
t2.start();
t3.start();
t4.start();
Thread.currentThread().getThreadGroup().list();
System.out.println(Thread.currentThread().getThreadGroup().activeCount());
System.out.println(Thread.currentThread().getThreadGroup().activeGroupCount());
// Main thread waits for all threads to complete
t1.join();
t2.join();
t3.join();
t4.join();
System.out.println("-----------------");
Thread.currentThread().getThreadGroup().list();
System.out.println(Thread.currentThread().getThreadGroup().activeCount());
System.out.println(Thread.currentThread().getThreadGroup().activeGroupCount());
}
}
You will see that even though all threads in child thread groups of Main have died, still thread groups exist except the last one which we marked as daemon thread group.