Skip to content
Advertisement

Why does Thread.activeCount() count more threads than my code creates?

I’m a beginner in Java development and i trying to write a multi threading process with using CountDownLatch in below code. But ExecutorService not working as it should.

ExecutorService thread number not working as it defined in code.

JavaScript

Console log;

JavaScript

I defined thread number as 50, but when it works Thread.activeCount() function returns 81. Why ?

Advertisement

Answer

You are using Thread.activeCount() which returns (an estimate of) the number of threads in the caller thread’s ThreadGroup.

This is not the same as querying how many thread is using your fixed size thread pool (you know the answer already, since you’ve created it).

As the others have said, you’re not the only creating threads, specifically, you’re not the only one creating threads in what is (I’m guessing) the ThreadGroup of your main Thread.

The executor you’ve created will create threads that are beloging to the ThreadGroup of the thread where you are actually instantiating it, so you will always have a higher count than your thread pool size.

If you want to see (for educational and debugging purposes) the complete picture of all threads in your jvm and what they’re doing (i.e. their stacktrace), try using jstack (it should be bundled in your JDK of choice).

https://docs.oracle.com/en/java/javase/11/tools/jstack.html

Advertisement