Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ExecutorService.submit work

I am trying to understand how Executor.submit(Runnable) works. Suppose we create a thread pool of size 2 using ExecutorService.

We have a class called Runner implements Runnable.

ExecutorService.newFixedThreadPool(2);
for (int i = 0; i <5; i++){
  ExecutorService.submit(new Runner());
}

When we do new Runner() are we not creating 5 threads already?

So how does ExecutorService help in this case?

like image 708
manojpotla Avatar asked May 25 '26 02:05

manojpotla


1 Answers

The service uses a queue to store the incoming Runnable objects. As soon as a thread becomes available to do work, the service uses that thread to execute the next Runnable object that is due.

Runnables are not Threads. Your example will create two threads which make up the pool; and then the 5 Runner objects will be dispatched to one of those two threads over time.

That is all there is to this.

like image 158
GhostCat Avatar answered May 26 '26 16:05

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!