views:

2505

answers:

4

Any ideas how to determine the number of active threads running in ExecutorService?

+5  A: 

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.

Daan
A: 

Place a static volatile counter on the thread which is updated whenever the thread is activated and deactivated. Also, see the API.

Javaxpert
+2  A: 

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, oder use the above code directly to obtain one. You can then invoke getActiveCount().

Arno
+1  A: 

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());
    }
}
Dave Cheney