2

I´m looking for best practices and I´m applying PMD to my Java EE Project, but one rule says that I have to avoid using java.lang.ThreadGroup, and I´m using it right now.

The rule says that is not safe, and I want to know: Why? Thanks

subsub
  • 1,857
  • 10
  • 21
Ocepeda
  • 37
  • 5
  • Possibly it's just because some (deprecated) methods are not thread-safe like `stop` and `suspend`. Although that would be a strange reasoning unless there is also a rule that says avoid using Thread (which also has unsafe `stop` and `suspend` methods). – subsub Sep 19 '13 at 14:57

1 Answers1

3

The concept of using ThreadGroup for security reasons has been abandoned as there is no controllable relationship between a Thread(Group) and the actual code it is executing. Even the most privileged thread could run insecure code and thus elevate that code to an undesired level. Therefore the code being executed itself (and its origin) is used for deciding which permission it has. So the executing thread and its group does not play any role to security in any way.

So after that, ThreadGroup offers no real functionality. It just became obsolete, only maintained for historical reasons. The only functionality which did not work without was uncaughtException(Thread t, Throwable e). But since Java 5 there is Thread.setUncaughtExceptionHandler( UncaughtExceptionHandler) so now even that works without thread groups.

Yes, a lot of ThreadGroups methods are not thread-safe and there was no attempt to fix them, just because they’re obsolete anyway.

Joshua Bloch writes in “Effective Java”:

Thread groups are best viewed as an unsuccessful experiment, and you should simply ignore their existence.

Holger
  • 285,553
  • 42
  • 434
  • 765
  • How should a failing thread interrupt a group of threads? Imagine N threads with infinite loops, if one of those is interrupted all of them needs to finish. Thread group way is simple to implement, but what would you suggest if that's not the best way? – svlada Oct 11 '22 at 13:42
  • 1
    @svlada you are thinking in wrong terms. You have a group of *tasks* and you should use an `ExecutorService` instead of dealing with threads manually. For example, [`invokeAny`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/ExecutorService.html#invokeAny(java.util.Collection)) will already cancel all tasks once one of them finished. For your specific scenario, submit your tasks, remember the futures and cancel all of them whenever you want. – Holger Oct 11 '22 at 16:20