Thread Group in JAVA

Thread Group in JAVA

Tasks are a logical unit of work, we use threads so that these tasks can run asynchronously. We know that there are two policies for executing a particular task using threads- execute them sequentially in a single thread and execute each task in its own thread. Both have respective disadvantages the prior has poor throughput and responsiveness while the other approach has the worst resource management. Therefore JAVA has a concept of a Thread group that offers better thread management.

What is a Thread Group?

Thread Group is a java class present in java.lang package and is a direct child class of Object.

fig1. Thread Group is a child class of Object

Based on the functionality of a thread we can group them into a single unit which is nothing but a Thread Group.

Thread Group contains a group of threads. They can also contain a Sub-Thread Group.

Fig2. A depiction of Thread Group

The advantage of Thread Group is that it becomes easy for us to perform common operations. The best example that we can consider is the Whatsapp group, we create a group so that we can send common messages instead of sending the same message to different individuals. The same thing is done in threads we group threads so that common functionalities can be performed easily, for example, by setting up priority to some particular threads we can set up maximum priority to all consumer threads and minimum priority to printer threads.

An Important Note

Every thread in JAVA belongs to some thread group.

Main Thread Group

Let us now consider an example of the main thread and check to which thread group it belongs.

class Test 
{
   public static void main(String[] args)
    {
      System.out.println(Thread.currentThread().getThreadGroup().getName());
    }
}

Output:

So we can see that the main thread belongs to a thread group called main.

But It must be noted that every thread group is a child group of the System group directly or indirectly.

System Thread Group

fig3. Different system threads

System Thread Group contains different system level threads For example:- Finalizer (i.e Garbage Collector), Reference Handler, Signal Dispatcher, Attach Listener and so on…

Let us now understand the below code snippet.

Here we can see that when we try to get the currentThread method we get main thread and when we call the ThreadGroup method we get main ThreadGroup and when we call getParent method we get system as the output.

Output:

Conclusion

Thread group class was created in JDK 1.0 to manage the state of multiple threads at once e.g suspend, resume, etc. The thread groups form a tree in which every thread group except the initial thread group has a parent.