0

I was wondering, what are the advantages of assigning threads to a thread group instead of containing them all in one (The Main) group?

Assuming there are 10 or more constantly active threads, and a couple of threads been initiated every now and again as the application requires, how would one approach grouping these?

Thanks, Adam.

TacB0sS
  • 10,106
  • 12
  • 75
  • 118

1 Answers1

3

There is no advantage at all. ThreadGroups are there for backward compatibility, but I've never seen them used.

Here's what Brian Goetz (author of Java Concurrency in Practice - the bible) said about them a long time ago:

The ThreadGroup class was originally intended to be useful in structuring collectionsof threads into groups. However, it turns out that ThreadGroup is not all that useful. You are better off simply using the equivalent methods in Thread. ThreadGroup does offer one useful feature not (yet) present in Thread: the uncaughtException() method. When a thread within a thread group exits becauseit threw an uncaught exception, the ThreadGroup.uncaughtException() method is called. This gives you an opportunity to shut down the system, write a message to a log file, or restart a failed service.

Threads now have an uncauht exception handler, and this single reason to use thread groups isn't valid anymore.

Gray
  • 115,027
  • 24
  • 293
  • 354
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Java debuggers aggregate threads according to their `ThreadGroup`, so I think that bookkeeping is one small reason to use them. For example, if one class will start up a few threads for different purposes, it can be nice to put each thread in a common group named for the class, and to give each thread a logical name. I agree that they should not be used for managing execution, though. – Brandon Jan 06 '17 at 17:03