Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Java FixedThreadPool

I am trying to understand how Java FixedThreadPool works in practice, but the docs do not answer my question.

Assume a simple scenario like:

ExecutorService ES= Executors.newFixedThreadPool(3);
List<Future> FL;
for(int i=1;i<=200;i++){
   FL.add(ES.submit(new Task()));
}
ES.shutdown();

where Task is a Callable which construct some resources, uses them, and returns some output.

My question: how many Task are there in memory upon completing the for loop? In other words: will there be only 3 Task at a time constructing their resources, or all of them are created upfront, such that, after .submit I have 200 Task (and their resources) waiting to execute?

Note: resources construction happens in the constructor of Task, not in the call() method.

In the javadoc (feel free to skip the following): what confuses me is the following explanation in the Java docs

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks.

I suppose this means that, in my example, all the 200 Task are in the queue, but only 3 of them are executed at any time.

Any help is highly appreciated.

like image 244
k88074 Avatar asked Mar 26 '15 11:03

k88074


1 Answers

Your code is equivalent to

for (int i = 1; i <= 200; i++){
    Task t = new Task();
    FL.add(ES.submit(t));
}

And after the for loop, the constructor of Task has thus been called 200 times, and the code it contains has thus been executed 200 times. Whether the task is submitted to an executor or not is irrelevant: you're invoking a constructor 200 times in a loop, and after each task has been constructed, it's submitted to the executor. The executor is not the one calling the task constructor.

like image 98
JB Nizet Avatar answered Oct 29 '22 12:10

JB Nizet