Java: how many threads are in a cached thread pool?

Posted by – Sunday 2011-07-17

The advent of multicore processors and the good thread support that Java has, have made this platform a good choice for parallel computing.

When distributing the workload among the created threads, questions like the optimum number and when to create and destroy them are important. Usually the answers to these questions are not obvious.

Fortunately, since Java 5 there is available a cached thread pool that can make our life a bit easier by – according to the API – creating «new threads as needed». Besides, this cached thread pool «will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will be created and added to the pool.» [1]

If using one of these cached thread pools, a question that might arise is “How many threads were created by this thread pool?” The following code snippet will give us the maximum number of threads.

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


ExecutorService myCachedThreadPool = Executors.newCachedThreadPool();


int largestPoolSize =
 ((ThreadPoolExecutor) myCachedThreadPool).getLargestPoolSize();
System.out.printf("cached thread pool largest size was %d threadsn", largestPoolSize);


The class java.util.concurrent.TheadPoolExecutor has also other interesting methods. For instance:

  • The method getPoolSize() returns the current number of threads the pool has.
  • The method getActiveCount() returns the number of threads that currently are working (that is, not idle),
  • The method setKeepAliveTime() will allow us to modify the time a thread is idle before it is terminated.

Last but not least, note the kind of workload this cached thread pool is suitable for: «programs that execute many short-lived asynchronous tasks».


[1] class java.util.concurrent.Executors, method newCachedThreadPool():

0 Comments on Java: how many threads are in a cached thread pool?