javamultithreadingthreadpool

Java ThreadPoolExecutor - FixedThreadPool ActiveCount = 0, QueueSize = 1, PoolSize = 10


I am creating Java thread pool using FixedThreadPool with a pool size of 10.

From the constructor, it is

    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

That means I created a thread pool with core thread pool size 10 and maximum thread pool size of 10. According to the Java 8 official doc, this means that:

  1. There will be a maximum of 10 threads, regardless how much requests coming in
  2. The queue will grow indefinitely

When checking the counters however, I got confused with the following counter:

The above counter show up a coupe of times so it is not just an one off situation. I also see some counters like this:

In this case a request is still in the queue while there are less than pool size of threads are actively processing tasks. Does anyone know why this happen? Am I missing anything here?


Solution

  • This is an artefact due to race conditions.

    If you look at the example that markspace provided:

        public static void main(String[] args) {
           ExecutorService es = Executors.newFixedThreadPool(10);
           System.out.println(es);
           for (int i = 0; i < 20; i++) {
              es.execute(() -> System.out.println("test"));
           }
           System.out.println(es);
           es.shutdown();
        }
    

    It creates a fixed threadpool of size 10 and then submits 20 tasks in short succession.

    For the first 10 tasks worker threads are created and started immediately, the other 10 tasks are added to the work queue.

    That 10 worker threads are created is shown by the "pool size = 10":

    When you print out the state of the thread pool using System.out.println(es); the thread pools toString() method gathers some statistics:

    Returns a string identifying this pool, as well as its state, including indications of run state and estimated worker and task counts.

    These values are not exact because the toString() method does not pause any workers while gathering the statistics.