
org.sonar.l10n.java.rules.java.S3014.html Maven / Gradle / Ivy
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
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
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
- CERT, THI01-J. - Do not invoke ThreadGroup methods
© 2015 - 2025 Weber Informatics LLC | Privacy Policy