What is the benefit of ThreadGroup in java over creating separate threads?
Using ThreadGroup
can be a useful diagnostic technique in big application servers with thousands of threads. If your threads are logically grouped together, then when you get a stack trace you can see which group the offending thread was part of (e.g. "Tomcat threads", "MDB threads", "thread pool X", etc), which can be a big help in tracking down and fixing the problem.
Somewhat complimentary to the answer provided (6 years ago or so). But, while the Concurrency API provides a lot of constructs, the ThreadGroup
might still be useful to use. It provides the following functionality:
- Logical organisation of your threads (for diagnostic purposes).
- You can
interrupt()
all the threads in the group. (Interrupting is perfectly fine, unlikesuspend()
,resume()
andstop()
). - You can set the maximum priority of the threads in the group. (not sure how widely useful is that, but there you have it).
- Sets the
ThreadGroup
as a daemon. (So all new threads added to it will be daemon threads). - It allows you to override its
uncaughtExceptionHandler
so that if one of the threads in the group throws an Exception, you have a callback to handle it. - It provides you some extra tools such as getting the list of threads, how many active ones you have etc. Useful when having a group of worker threads, or some thread pool of some kind.
Don't use ThreadGroup
for new code. Use the Executor
stuff in java.util.concurrent
instead.