Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki Markup
A {{ThreadGroup}} is a group of threads as defined by the class {{java.lang.ThreadGroup}}. A group is assigned to a thread upon its creation. If the group name is not specified explicitly, the default group called {{main}} is assigned by the Java Virtual Machine (JVM). The convenience methods of the {{ThreadGroup}} class can be used to operate on all threads at once, such as, by using the {{interrupt()}} method. Another use is to build inreinforce layered security by confining threads into groups so that they do not interfere with each other.  
\[[JavaThreads 04|AA. Java References#JavaThreads 04]\]

Wiki Markup
While there may be a few benefits, the associated dangers demand deeper insight into the real utility of the {{ThreadGroup}} class. Several of the {{ThreadGroup}} APIs ({{allowThreadSuspension, resume, stop, suspend}}) have been deprecated and the remainder are seldom used duebecause they tooffer little desirable functionality. Ironically, a few APIs are not even thread-safe. \[[Bloch 01|AA. Java References#Bloch 01]\]

Wiki Markup
A programmer may sometimes wish to enumerate all the threads in a group as a precursor to other operations. This is accomplished by using the {{activeCount()}} method that "Returns an estimate of the number of active threads in this thread group. " \[[API 06|AA. Java References#API 06]\]. Notice that there is no absolute word on whether it returns the exact count or not; the definition of _active_ also has a different connotation here. A thread that is constructed and not started is still counted by the {{activeCount()}} method as _active_. 

Wiki Markup
According to the Java API \[[API 06|AA. Java References#API 06]\], Classclass {{ThreadGroup}} documentation:

The {{enumerate}} method " Copies into the specified array every active thread in this thread group and its subgroups. An application should use the activeCount method to get an estimate of how big the array should be. If the array is too short to hold all the threads, the extra threads are silently ignored. "

Wiki Markup
Threads are removed from the thread array either when they are stopped or when their {{run}} method has concluded. As a result, if a thread is not started, it continues to reside in the array despite the loss of the original reference. \[[JavaThreads 99|AA. Java References#JavaThreads 99]\]

...

There is a Time of Check-Time of Use (TOCTOU) vulnerability in this implementation because obtaining the count and enumerating the list do not constitute an atomic operation. If new requests come in during the time interval between calling activeCount() and enumerate(), the total number of threads in the group will increase but there would be the enumerated list ta will contain only two thread references in the enumerated list ta. Print statements have been added before the invocation of activecount() and enumerate() to show this effect. Different runs of the program produce different values because of the race conditions and demonstrate how a few incoming requests can get completely ignored. Any subsequent use of the ta array may lead to undesirable object retention.

Code Block
bgColor#FFcccc
class NetworkHandler implements Runnable {
  private static ThreadGroup tg = new ThreadGroup("Chief");
  public void run() {
    try {
      method1();
      method2();
      Thread.sleep(500);		
    } catch(InterruptedException e) {
      // Forward to handler
    }
  }

  public static void method1() throws InterruptedException {
    Thread t1 = new Thread(tg, new HandleRequest(), "t1");
    Thread t2 = new Thread(tg, new HandleRequest(), "t2");
    t1.start(); 
    t2.start(); 	
  }

  public static void method2() {			  
    Thread t3 = new Thread(tg, new HandleRequest(), "t3");
    Thread t4 = new Thread(tg, new HandleRequest(), "t4");		
    t3.start();
    t4.start();
  }
	
  public static void main(String[] args) throws InterruptedException {
    Thread t = new Thread(tg, new NetworkHandler(), "t");
    t.start();
    System.out.println("Active Threads in Thread Group at point (1):" +
        t.getThreadGroup().getName() + " " + Thread.activeCount());
    Thread ta[] = new Thread[Thread.activeCount()];
		
    for(int i = 0;i<500000; i < 500000; i++) { } // delayDelay to demonstrate TOCTOU condition
		
    System.out.println("Active Threads in Thread Group at point (2):" +
        t.getThreadGroup().getName() + " " + Thread.activeCount());
		
    int n = Thread.enumerate(ta);
    System.out.println("Enumerating...");
    for(int i = 0;i< i < n; i++) {
      System.out.println("Thread " + i + " = " + ta[i].getName());
    } 
  }
} 

class HandleRequest implements Runnable {
  public void run() {
    System.out.println("Active Threads in Thread Group (Handler thread invoked this): " + 
    Thread.currentThread().getThreadGroup().getName() + " " + Thread.activeCount());
		
  }
}

Compliant Solution

Wiki Markup
To be compliant, avoid using the {{ThreadGroup}} class. Before Java 5.0, this class had to be extended as there was no other way to control the {{UncaughtExceptionHandler}}. ThisThe application provided handler {{UncaughtExceptionHandler}} comes into the picture when a thread exits because of an uncaught exception. In recent versions, the {{UncaughtExceptionHandler}} is maintained on a per-thread basis using an interface enclosed by the {{Thread}} class, leaving little to no functionality for the {{ThreadGroup}} class. \[[Goetz 06|AA. Java References#Goetz 06]\] 

...