Kindly help me in understanding the internal flow of newFixedThreadPool (or Cached)
When we write below statements, ExecutorService e=Executors.newFixedThreadPool(3)
FYI: Here is a very simple implementation of a thread pool.
class MyThreadPool implements java.util.concurrent.Executor
{
private final java.util.concurrent.BlockingQueue queue;
public MyThreadPool(int numThreads) {
queue = new java.util.concurrent.LinkedBlockingQueue<>();
for (int i=0 ; i
This won't compile because I didn't deal with InterruptedException, and in a real thread pool, you would also want to deal with exceptions that might be thrown by the given command
, but it should give you a rough idea of what a thread pool does.
It creates a queue and an arbitrary number of worker threads. The worker threads compete with one another to consume commands from the queue. The queue is a BlockingQueue
, so the workers all sleep whenever the queue is empty.
Other threads may produce new commands (i.e., Runnable
objects), and call the execute(command)
method to put the new commands in the queue. The commands will be performed (i.e., their run methods will be called) by the worker threads in approximately* the same order that they were enqueued.
.run()
method. Other workers could then pick other commands from the queue and perform them before the scheduler allows worker A to run again.