Active threads in ExecutorService

The ExecutorService interface does not define a method to examine the number of worker threads in the pool, as this is an implementation detail

public int getPoolSize()
Returns the current number of threads in the pool.

Is available on the ThreadPoolExecutor class

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class PoolSize {

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue());
        System.out.println(executor.getPoolSize());
    }
}

But this requires you to explicitly create the ThreadPoolExecutor, rather than using the Executors factory which returns ExecutorService objects. You could always create your own factory that returned ThreadPoolExecutors, but you would still be left with the bad form of using the concrete type, not its interface.

One possibility would be to provide your own ThreadFactory which creates threads in a known thread group, which you can then count

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;


public class PoolSize2 {

    public static void main(String[] args) {
        final ThreadGroup threadGroup = new ThreadGroup("workers");

        ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {
            public Thread newThread(Runnable r) {
                return new Thread(threadGroup, r);
            }
        });

        System.out.println(threadGroup.activeCount());
    }
}

Check the sourcecode for Executors.newFixedThreadPool():

return new ThreadPoolExecutor(nThreads, nThreads,
                              0L, TimeUnit.MILLISECONDS,
                              new LinkedBlockingQueue<Runnable>());

ThreadPoolExecutor has a getActiveCount() method. So you might either cast the ExecutorService to ThreadPoolExecutor, or use the above code directly to obtain one. You can then invoke getActiveCount().


Assuming pool is the name of the ExecutorService instance:

if (pool instanceof ThreadPoolExecutor) {
    System.out.println(
        "Pool size is now " +
        ((ThreadPoolExecutor) pool).getActiveCount()
    );
}

Use a ThreadPoolExecutor implementation and call getActiveCount() on it:

int getActiveCount() 
// Returns the approximate number of threads that are actively executing tasks.

The ExecutorService interface does not provide a method for that, it depends on the implementation.