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 ...

Get Java Threads, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.