Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migration of unmigrated content due to installation of a new plugin

Wiki MarkupA {{ThreadGroup}} is nothing but a group of threads as defined by the class {{Each thread in Java is assigned to a thread group upon the thread's creation. These groups are implemented by the 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 JVM. One can use the convenience methods of the {{ThreadGroup}} class to operate on all threads at once, such as, by using the {{interrupt}} method. Another use is to build in layered security by confininf 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 a 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 due to 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; the definition of _active_ also has a different connotation here. A thread that has been constructed and not started is still counted by the {{activeCount}} method as _active_. [\PL. CONFIRM] 

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

...

class. When the thread group name is not specified explicitly, the main default group is assigned by the Java Virtual Machine (JVM) [Java Tutorials]. The convenience methods of the ThreadGroup class can be used to operate on all threads belonging to a thread group at once. For instance, the ThreadGroup.interrupt() method interrupts all threads in the thread group. Thread groups also help reinforce layered security by confining threads into groups so that they avoid interference with threads in other groups [JavaThreads 2004].

Even though thread groups are useful for keeping threads organized, programmers seldom benefit from their use because many of the methods of the ThreadGroup class (for example, allowThreadSuspension(), resume(), stop(), and suspend()) are deprecated. Furthermore, many nondeprecated methods are obsolete in that they offer little desirable functionality. Ironically, a few ThreadGroup methods are not even thread-safe [Bloch 2001].

Insecure yet nondeprecated methods include

  • ThreadGroup.activeCount()
    According to the Java API [API 2014], the activeCount() method

    returns an estimate of the number of active threads in the current thread's thread group and its subgroups.

    This method is often used as a precursor to thread enumeration. Threads that have never started nevertheless reside in the thread group and are considered to be active. The active count is also affected by the presence of certain system threads [API 2014]. Consequently, the activeCount() method might fail to reflect the actual number of running tasks in the thread group.
  • ThreadGroup.enumerate()
    According to the Java API [API 2014], ThreadGroup class documentation

    [The enumerate() method] copies into the specified array every active thread in this thread group and its subgroups....
    An application

...

  • might use the activeCount method to get an estimate of how big the array should be

...

  • ; however, if the array is too short to hold all the threads, the extra threads are silently ignored.

...

Using the ThreadGroup APIs to shut down threads also has pitfalls. Because the stop() method is deprecated, programs require alternative methods to stop threads. According to The Java Programming Language [JPL 2006]:

One way is for the thread initiating the termination to join the other threads and so know when those threads have terminated. However, an application may have to maintain its own list of the threads it creates because simply inspecting the ThreadGroup may return library threads that do not terminate and for which join will not return.

The Executor framework provides a better API for managing a logical grouping of threads and offers secure facilities for handling shutdown and thread exceptions [Bloch 2008]. Consequently, programs must not invoke ThreadGroup methods. Wiki MarkupThreads are removed from the thread array either when they are stopped or when their {{run}} method has concluded. Thus, if a thread is not started, it will continue to reside in the array despite the loss of the original reference. \[[JavaThreads 99|AA. Java References#JavaThreads 99]\]

Noncompliant Code Example

This noncompliant code example shows contains a NetworkHandler class that maintains a controller thread. This thread is responsible for spawning a new thread every time a new network connection request is received. For the sake of brevity, it is assumed that the controller thread invokes two methods (method1 and method2) in succession and waits for a few milliseconds. The method1 method creates and starts two threads that are equivalent to two consequent connection requests, and so does the method2 methodThe controller thread delegates each new request to a worker thread. To demonstrate the race condition in this example, the controller thread serves three requests by starting three threads in succession from its run() method. All threads are defined to belong to the same group, Chief.There is a Time of Check-Time of Use (TOCTOU) vulnerability in this implementation since obtaining the count and enumerating the list are not 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 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 would produce different values due to the race conditions and demonstrate how a few incoming requests can get completely ignored. Any subsequent usage of the ta array would lead to undesirable object retention. Chief thread group.

Code Block
bgColor#FFcccc
final class HandleRequest implements Runnable {
  public void run() {
    // Do something
  }
}

public final class NetworkHandler implements Runnable {
  private static ThreadGroup tg = new ThreadGroup("Chief");

  @Override public void run() {

    try {
          method1new Thread(tg, new HandleRequest(), "thread1").start();
    new Thread(tg, new    method2HandleRequest(), "thread2").start();
    new Thread(tg, new    Thread.sleep(500);		
    } catch(InterruptedException e) {}
  }HandleRequest(), "thread3").start();
  }

  public static void method1printActiveCount(int point) {
 throws InterruptedException {
    System.out.println("Active Threads in Thread t1Group =" new+ Thread(tg, new HandleRequesttg.getName(), "t1");+
    Thread t2 = new Thread(tg, new HandleRequest(), "t2");
    t1.start(); 
    t2.start(); 	" at point(" + point + "):" + " " + tg.activeCount());
  }

  public static void method2() {			  
    Thread t3 = new Thread(tg, new HandleRequest(), "t3");printEnumeratedThreads(Thread[] ta, int len) {
    System.out.println("Enumerating all threads...");
    for (int i = 0; i < len; i++) {
    Thread t4 = new Thread(tg, new HandleRequest(), "t4");		
    t3.start() System.out.println("Thread " + i + " = " + ta[i].getName());
    t4.start();}
  }
	
  public static void main(String[] args) throws InterruptedException {
    // Start thread controller
    Thread tthread = new Thread(tg, new NetworkHandler(), "tcontroller");
    tthread.start();

    System.out.println("Active Threads in Thread Group at point (1):" + t.getThreadGroup().getName() + " " + Thread.activeCount());// Gets the active count (insecure)
    Thread[] ta[] = new Thread[Threadtg.activeCount()];
		
    for(int i=0;i<500000;i++) {}printActiveCount(1); // P1
    // delayDelay to demonstrate TOCTOU condition
		 (race window)
    SystemThread.out.println("Active Threads in Thread Group at point (2):" + t.getThreadGroup().getName() + " " + Thread.activeCount());
		
sleep(1000);
    // P2: the thread count changes as new threads are initiated
    printActiveCount(2);  
    // Incorrectly uses the (now stale) thread count obtained at P1
    int n = Threadtg.enumerate(ta);  
    //  System.out.println("Enumerating...");
    for(int i=0;i< n;i++) {
      System.out.println("Thread " + i + " = " + ta[i].getNameSilently ignores newly initiated threads 
    printEnumeratedThreads(ta, n); 
                                   // (between P1 and P2)

    // This code destroys the thread group if it does 
    // not have any live threads
    for (Thread thr : ta) {
      thr.interrupt();
      while(thr.isAlive());
    }
    tg.destroy();
  }
} 

class HandleRequest implements Runnable {
  public void run(

This implementation contains a time-of-check, time-of-use (TOCTOU) vulnerability because it obtains the count and enumerates the list without ensuring atomicity. If one or more new requests were to occur after the call to activeCount() and before the call to enumerate() in the main() method, the total number of threads in the group would increase, but the enumerated list ta would contain only the initial number, that is, two thread references: main and controller. Consequently, the program would fail to account for the newly started threads in the Chief thread group.

Any subsequent use of the ta array would be insecure. For example, calling the destroy() method to destroy the thread group and its subgroups would not work as expected. The precondition to calling destroy() is that the thread group must be empty with no executing threads. The code attempts to comply with the precondition by interrupting every thread in the thread group. However, the thread group would not be empty when the destroy() method was called, causing a java.lang.IllegalThreadStateException to be thrown.

Compliant Solution

This compliant solution uses a fixed thread pool rather than a ThreadGroup to group its three tasks. The java.util.concurrent.ExecutorService interface provides methods to manage the thread pool. Although the interface lacks methods for finding the number of actively executing threads or for enumerating the threads, the logical grouping can help control the behavior of the group as a whole. For instance, invoking the shutdownPool() method terminates all threads belonging to a particular thread pool.

Code Block
bgColor#ccccff
public final class NetworkHandler {
  private final ExecutorService executor;

  NetworkHandler(int poolSize) {
  System.out.println("Active Threads in Thread Group (Handler thread invoked this): " + Thread.currentThread().getThreadGroup().getName() + " " + Thread.activeCount());
		  this.executor = Executors.newFixedThreadPool(poolSize);
  }

  public void startThreads() {
    for (int i = 0; i < 3; i++) {
      executor.execute(new HandleRequest());
    }
  }
}

Compliant Solution

...

 

...

 

...

public 

...

void 

...

shutdownPool() 

...

{
    executor.shutdown();
  }

  public static void main(String[] args)  {
    NetworkHandler nh = new NetworkHandler(3);
    nh.startThreads();
    nh.shutdownPool();
  }
}

Before Java SE 5.0, applications that needed to catch an uncaught exception in a separate thread had to extend the ThreadGroup class because this was the only direct approach to provide the required functionality. Specifically, an application's UncaughtExceptionHandler could only be controlled by subclassing ThreadGroup. In more recent versions of Java, UncaughtExceptionHandler is maintained on a per-thread basis using an interface enclosed by the Thread class. Consequently, the ThreadGroup class provides little unique functionality [Goetz 2006], [Bloch 2008].

Refer to TPS03-J. Ensure that tasks executing in a thread pool do not fail silently for more information on using uncaught exception handlers in thread pools.

Risk Assessment

Use of

Risk Assessment

Using the ThreadGroup APIs may result in race conditions, memory leakage leaks, and inconsistent object state.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

SEC01

THI01-J

low

Low

unlikely

Probable

low

Medium

P3

P4

L3

Automated Detection

...

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[API 06|AA. Java References#API 06]\] Methods {{activeCount}} and {{enumerate}}, Classes ThreadGroup and Thread
\[[JavaThreads 04|AA. Java References#JavaThreads 04]\] 13.1 ThreadGroups
\[[Bloch 01|AA. Java References#Bloch 01]\] Item 53: Avoid thread groups
\[[Goetz 06|AA. Java References#Goetz 06]\] 7.3.1. Uncaught Exception Handlers
\[[SDN 06|AA. Java References#SDN 06]\] Bug ID: 4089701 and 4229558

ToolVersionCheckerDescription
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.THI01.AUTGDo not use variables of the unsafe type 'java.lang.ThreadGroup'
SonarQube
Include Page
SonarQube_V
SonarQube_V
S3014"ThreadGroup" should not be used

Bibliography

[API 2006]

Class Thread
Class ThreadGroup:
  Method activeCount
  Method enumerate

[Bloch 2001]

Item 53, "Avoid Thread Groups"

[Bloch 2008]

Item 73, "Avoid Thread Groups"

[Goetz 2006]

Section 7.3.1, "Uncaught Exception Handlers"

[JavaThreads 2004]

Section 13.1, "ThreadGroups"

[Java Tutorials]

[JPL 2006]

Section 23.3.3, "Shutdown Strategies"

[SDN 2006]

Bug ID 4089701
Bug ID 4229558


...

Image Added Image Added Image AddedCON00-J. Use synchronization judiciously      08. Concurrency (CON)      CON02-J. Facilitate thread reuse by using Thread Pools