Creating Java ThreadGroup Example

You may notice that as your multithreaded applications become more involved and complex the number of threads that you will be managing will likely become quite large. When this occurs, it may become necessary to create thread groups to aid in the management and organization of the threads. Every thread in JVM belongs to some thread group even if you, as the programmer, never specified any when the thread was created. By default, any newly created thread will belong to main thread group unless you specify otherwise at the time of creation.

Note

The assigning of a thread to a particular thread group can only be done at creation time otherwise it will be assigned to the main thread group implicitly. Once a thread has been assigned a thread group, this thread group will remain for the entire duration of the thread’s lifetime.

Thread groups may contain any number of threads, with the groupings somehow related by function, creator, or activity they perform. In addition, thread groups can themselves contain other thread groups inside of them forming a tree hierarchy as depicted in the figure below.

thread groups

Benefits of using Thread Groups

  • Creates a logical grouping of related threads
  • Provides collective thread management
  • Get Aggregate CPU usage for the group of threads
  • Stack trace reveals thread group names providing more insight into offending thread

ThreadGroup Methods

MethodDescription
ThreadGroup(String name)Create a thread group with thread group name
ThreadGroup(String parent, String name)Create a thread group under parent with thread group name
int activeCount()Returns the estimated of the number of active threads in the thread group and its subgroups
int activeGroupCount()Returns the estimated of the number of active groups in the thread group and its subgroups
int getMaxPriority()Returns the maximum priority of the thread group
String getName()Returns the maximum priority of the thread group
int getParent()Returns the parent of the thread group
void interrupt()Interrupts all threads in the thread group
boolean isDaemon()Tests if the thread group is a daemon thread group
boolean isDestroyed()Tests if the thread group has been destroyed
void list()Prints information about this thread group to the standard output
void setDaemon(boolean daemon)Changes the daemon status of the thread group
void setMaxPriority(int pri)Sets the maximum priority of the thread group
String toString()Returns a string representation of the Thread group

Thread Group Construction and Usage

You construct a thread group with one of the two constructors available to us. In this case, I am using the single argument constructor for MsgThreads and the two argument constructor for JmsThreads since they are a subgroup inside of MsgThreads. The string argument identifies the group and must be unique. You then add the threads to the thread group by specifying the thread group in the thread constructor.

ThreadGroup MsgThreads = new ThreadGroup("MsgThreads");
ThreadGroup JmsThreads = new ThreadGroup(MsgThreads, "JMSThreads");
Thread mt1 = new MyThread(MsgThreads, "msgThread_1");

ThreadGroupExample.java

In my example below, I will simulate only part of the thread group tree structure I depicted above. This java program will have three thread groups: the MsgThreads group, the JmsThreads group and the EmailThreads group. The MsgThreads group will only have one thread under it, the JmsThreads group will have two threads and the EmailThreads group will have three threads.

package com.avaldes.tutorials;

public class ThreadGroupExample {

  public static void main(String[] args) {

    ThreadGroup MsgThreads = new ThreadGroup("MsgThreads");
    ThreadGroup JmsThreads = new ThreadGroup(MsgThreads, "JMSThreads");
    ThreadGroup EmailThreads = new ThreadGroup(MsgThreads, "EmailThreads");

    MyThread mt1 = new MyThread(MsgThreads, "msgThread_1");
    MyThread jt1 = new MyThread(JmsThreads, "jmsThread_1");
    MyThread jt2 = new MyThread(JmsThreads, "jmsThread_2");
    MyThread et1 = new MyThread(EmailThreads, "emailThread_1");
    MyThread et2 = new MyThread(EmailThreads, "emailThread_2");
    MyThread et3 = new MyThread(EmailThreads, "emailThread_3");
    
    //startup msg thread
    mt1.start();
    
    //startup jms threads
    jt1.start();
    jt2.start();

    //startup email threads
    et1.start();
    et2.start();
    et3.start();
    
    System.out.println("MsgThreads ThreadGroup Details");
    System.out.println("ThreadGroup Name....: " + MsgThreads.getName());
    System.out.println("ThreadGroup Parent..: " + MsgThreads.getParent());
    System.out.println("Active Count........: " + MsgThreads.activeCount());
    System.out.println("Active Group Count..: " + MsgThreads.activeGroupCount());
    System.out.println("Max Priority........: " + MsgThreads.getMaxPriority());
    MsgThreads.setMaxPriority(6);   
    System.out.println("Setting Group Priority to 6");
    System.out.println("Max Priority........: " + MsgThreads.getMaxPriority());
    
    System.out.println("\nEmail ThreadGroup Details");
    System.out.println("Attempting to set Group Priority to 8 -- should not work!!!");
    EmailThreads.setMaxPriority(8);  // Will not succeed as it exceed the maximum set by parent thread group
    System.out.println("ThreadGroup Name....: " + EmailThreads.getName());
    System.out.println("ThreadGroup Parent..: " + EmailThreads.getParent());
    System.out.println("Active Count........: " + EmailThreads.activeCount());
    System.out.println("Active Group Count..: " + EmailThreads.activeGroupCount());
    System.out.println("Max Priority........: " + EmailThreads.getMaxPriority());

    System.out.println("\nEmail ThreadGroup Details");
    System.out.println("Attempting to set Group Priority to 4");
    EmailThreads.setMaxPriority(4);  // This will work
    System.out.println("ThreadGroup Name....: " + EmailThreads.getName());
    System.out.println("ThreadGroup Parent..: " + EmailThreads.getParent());
    System.out.println("Active Count........: " + EmailThreads.activeCount());
    System.out.println("Active Group Count..: " + EmailThreads.activeGroupCount());
    System.out.println("Max Priority........: " + EmailThreads.getMaxPriority());

    System.out.println("\nJMS ThreadGroup Details");
    System.out.println("ThreadGroup Name....: " + JmsThreads.getName());
    System.out.println("ThreadGroup Parent..: " + JmsThreads.getParent());
    System.out.println("Active Count........: " + JmsThreads.activeCount());
    System.out.println("Active Group Count..: " + JmsThreads.activeGroupCount());
    System.out.println("Max Priority........: " + JmsThreads.getMaxPriority());
  }
}

MyThread.java

package com.avaldes.tutorials;

public class MyThread extends Thread {
  private int counter = 0;
  
  MyThread(String name) {
    super(name);
    System.out.println("Creating Thread: " + name);
  }
  
  MyThread(ThreadGroup group, String name) {
    super(group, name);
  }
  
  @Override
  public void run() {
    while (counter < 10) {
      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      
    }
  }
}

Output

MsgThreads ThreadGroup Details
ThreadGroup Name....: MsgThreads
ThreadGroup Parent..: java.lang.ThreadGroup[name=main,maxpri=10]
Active Count........: 6
Active Group Count..: 2
Max Priority........: 10
Setting Group Priority to 6
Max Priority........: 6

Email ThreadGroup Details
Attempting to set Group Priority to 8 -- should not work!!!
ThreadGroup Name....: EmailThreads
ThreadGroup Parent..: java.lang.ThreadGroup[name=MsgThreads,maxpri=6]
Active Count........: 3
Active Group Count..: 0
Max Priority........: 6

Email ThreadGroup Details
Attempting to set Group Priority to 4
ThreadGroup Name....: EmailThreads
ThreadGroup Parent..: java.lang.ThreadGroup[name=MsgThreads,maxpri=6]
Active Count........: 3
Active Group Count..: 0
Max Priority........: 4

JMS ThreadGroup Details
ThreadGroup Name....: JMSThreads
ThreadGroup Parent..: java.lang.ThreadGroup[name=MsgThreads,maxpri=6]
Active Count........: 2
Active Group Count..: 0
Max Priority........: 6

Related Posts

  • Java Thread, Concurrency and Multithreading Tutorial
    This Java Thread tutorial will give you a basic overview on Java Threads and introduce the entire tutorial series on concurrency and multithreading. From here, you will learn about many java thread concepts like: Thread States, Thread Priority, Thread Join, and ThreadGroups. In addition, you will learn about using the volatile keyword and examples on using wait, notify and notifyAll.
  • Java Thread States - Life Cycle of Java Threads
    Get a basic understanding of the various thread states. Using the state transition diagram we show the various states for a Java thread and the events that cause the thread to jump from one state to another.
  • Creating Java Threads Example
    In this post we cover creating Java Threads using the two mechanisms provided in Java, that is, by extending the Thread class and by implementing Runnable interface for concurrent programming.
  • Java Thread Priority Example
    In this post we cover Thread priorities in Java. By default, a java thread inherits the priority (implicit) of its parent thread. Using the setPriority() method you can increase or decrease the thread priority of any java thread.
  • Java ThreadGroup Example
    Sometimes we will need to organize and group our threads into logical groupings to aid in thread management. By placing threads in a threadGroup all threads in that group can be assigned properties as a set, instead of going through the tedious task of assigning properties individually.
  • Java Thread Sleep Example
    We seem to use this method very often to temporarily suspend the current threads execution for a specific period of time. Let's spend some time and familiarize ourselves with what this method actually does.
  • Java Thread Join Example
    In Java, using Thread.join() causes the current thread to wait until the specified thread dies. Using this method allows us to impose an order such that we can make one thread wait until the other completes doing what it needed to do, such as completing a calculation.
  • Examining Volatile Keyword with Java Threads
    When we declare a field as volatile, the JVM will guarantee visibility, atomicity and ordering of the variable. Without it the data may be cached locally in CPU cache and as a result changes to the variable by another thread may not be seen by all other threads resulting in inconsistent behaviour.
  • Java Threads Wait, Notify and NotifyAll Example
    The purpose of using notify() and notifyAll() is to enable threads to communicate with one another via some object on which to performing the locking. A thread using the wait() method must own a lock on the object. Once wait() is called, the thread releases the lock, and waits for another thread to either call notify() or notifyAll() method.
  • Java Thread Deadlock Example and Thread Dump Analysis using VisualVM
    Deadlock is a condition where several threads are blocking forever, waiting for the other to finish but they never do. This tutorial will discuss situations that will lead to Java Thread deadlock conditions and how they can be avoided. In addition, we will discuss using Java VisualVM to pinpoint and analyze the source of the deadlock conditions.
  • Java Thread Starvation and Livelock with Examples
    Starvation occurs when a thread is continually denied access to resources and as a result it is unable to make progress. Thread liveLock is a condition that closely resembles deadlock in that several processes are blocking each other. But with livelock, a thread is unable to make any progress because every time it tries the operation always fails.
  • Java Synchronization and Thread Safety Tutorial with Examples
    One of Java's many strengths come from the fact that it supports multithreading by default as has so from the very onset. One of the mechanisms that Java uses for this is via synchronization. When we use the synchronized keyword in Java we are trying limit the number of threads that can simultaneously access and modify a shared resource. The mechanism that is used in Java's synchronization is called a monitor.
  • Creating a Thread Safe Singleton Class with Examples
    In this tutorial we cover many examples of creating thread-safe singleton classes and discuss some of the shortfalls of each and provide some recommendations on best approaches for a fast, efficient and highly concurrent solution.
  • Java Threads and Concurrent Locks with Examples
    In this tutorial we will focus primarily on using the concurrent utilities and how these can make concurrent programming easier for us.

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *