2

In the below code, Thread.activeCount() returns 2 always even though the thread in executor terminates after 5 seconds.

public class MainLoop {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(12);
        executor.submit(new Callable<Void>() {
            public Void call() throws Exception {
                Thread.sleep(5000);
                return null;
            }
        });
        while (true) {
            System.out.println(Thread.activeCount());
            Thread.sleep(1000);
        }
    }
}

I expected Thread.activeCount() to return 1 after 5 seconds. Why is it always returning 2 ?

user1
  • 45
  • 7
  • you should call `shutdown()` method as explained https://stackoverflow.com/questions/16122987/reason-for-calling-shutdown-on-executorservice – Prateek Jain Apr 22 '19 at 08:16

1 Answers1

4

See the docs of newFixedThreadPool. https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)

At any point, at most nThreads threads will be active processing tasks. The threads in the pool will exist until it is explicitly shutdown.

After a callable is submitted to this executor, it will be pricked up and processed by one of the threads of the pool. After completing this execution, the thread will sit idle in the pool waiting for a next callable.

Lesiak
  • 22,088
  • 2
  • 41
  • 65
  • 1
    If you do not like that, use a non-fixed thread pool. They let you configure how long you want to allow idle threads. – Thilo Apr 22 '19 at 08:09