The ExecutorService interface does not define a method for checking the number of worker threads in the pool, since this is an implementation detail
public int getPoolSize() Returns the current number of threads in the pool.
Available in 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 explicitly creating a ThreadPoolExecutor, and not using the Executors factory, which returns ExecutorService objects. You can always create your own factory, which returned ThreadPoolExecutors, but you will still be left with a bad form of using a particular type, rather than its interface.
One possibility is to provide your own ThreadFactory, which creates threads in a well-known thread group that you can 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 ());
}
}
Dave Cheney Sep 17 '08 at 7:43 2008-09-17 07:43
source share