rspec/rules/S3014/java/rule.adoc
2023-08-08 14:47:30 +02:00

62 lines
1.5 KiB
Plaintext

== Why is this an issue?
The `ThreadGroup` class contains many deprecated methods like `allowThreadSuspension`, `resume`, `stop`, and `suspend`.
Also, some of the non-deprecated methods are obsolete or not thread-safe, and still others are insecure (`activeCount`, `enumerate`).
For these reasons, any use of `ThreadGroup` is suspicious and should be avoided.
== How to fix it
Instead, use implementations of `java.util.concurrent.ExecutorService` to safely manage groups of threads.
=== Code examples
==== Noncompliant code example
[source,java]
----
class NetworkHandler {
void startThreadInGroup(ThreadGroup tg) { // Noncompliant, use an ExecutorService instead, which is more secure
Thread thread = new Thread(tg, "controller");
thread.start();
}
}
----
==== Compliant solution
[source,java]
----
class NetworkHandler {
void handleThreadsProperly() {
ThreadFactory threadFactory = Executors.defaultThreadFactory();
ThreadPoolExecutor executorPool = new ThreadPoolExecutor(3, 10, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2), threadFactory);
for (int i = 0; i < 10; i++) {
executorPool.execute(new Thread("Job: " + i));
}
executorPool.shutdown();
}
}
----
== Resources
* https://wiki.sei.cmu.edu/confluence/x/YzdGBQ[CERT, THI01-J.] - Do not invoke ThreadGroup methods
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Remove this use of "ThreadGroup". Prefer the use of "ThreadPoolExecutor".
endif::env-github,rspecator-view[]