Chapter 10. Thread Groups

In this chapter, we will discuss Java’s ThreadGroup class, which, as the name implies, is a class that handles groups of threads. Thread groups are useful for two reasons: they allow you to manipulate many threads by calling a single method, and they provide the basis that Java’s security mechanism uses to interact with threads. In Java 1.0, the actual use of thread groups was really limited to writers of Java applications: within an applet, virtually no operations on thread groups were possible, due in part to security restrictions (but also due in part to bugs in the API). This has changed in later releases of Java, so that thread groups may be used in any Java program.

Thread Group Concepts

Say that you’re writing a server using the TCPServer class we developed in Chapter 5. Each client that connects to the server runs as a separate thread. Now say that for each client, the server is going to create many other threads: perhaps a timer thread, a separate thread to read data coming from the client, another to write data to the client, and maybe some threads for a calculation algorithm. Well, you get the idea: the server has a lot of threads it needs to manage.

This is where the ThreadGroup class comes into play. Thread groups allow you to modify many threads with one call—making it easier to control your threads and making it less likely that you’ll forget one.

Although we haven’t yet mentioned thread groups, they’ve been around all along: all threads in the Java virtual machine belong to a thread group. Every thread you create automatically belongs to a default thread group the Java virtual machine sets up on your behalf. So all the threads that we’ve looked at so far belong to this existing thread group.

Thread groups are more than just arbitrary groupings of threads, however; they are related to each other. Every thread group (with the obvious exception of the first thread group) has a parent thread group, so the groups exist in a tree hierarchy. The root of this tree is known as the system thread group .

You can create your own thread groups as well; each thread group is the child of an existing thread group. In the TCPServer example we discussed earlier, the thread hierarchy might appear as shown in Figure 10.1.

A thread group hierarchy

Figure 10-1. A thread group hierarchy

We’ll end up with at least one thread group for each connected client; note that the thread groups have the option of creating other thread groups underneath them. Also note that the threads themselves are interspersed among the groups in the entire hierarchy: a thread group contains threads as well as (possibly) other thread groups.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset