How to create multiple threadpools i.e. multiple executors each with a single thread

869 Views Asked by At

I currently need to create multiple threadpools. Each threadpool is a single threaded threadpool. I assign tasks to each threadpool based upon a condition. So I need to maintain track of threadpools.

How can I do that? Can I create an array of threadpools?

ExecutorService executor = Executors.newSingleThreadExecutor();

This is how we create 1 threadpool. Now I want to create 5 threadpools.

ExecutorService[] executor;
for(int i=0;i<5;i++){
executor[i]= Executors.newSingleThreadExecutor();
}

Is this ok? Is this right syntax? If not, can you suggest a way to do it?

1

There are 1 best solutions below

1
On

In your scenario, I believe it is possible to use just one single thread Executor since according to the documentation:

Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.

Therefore with multiple input from multiple companies, the queue of the Executor will look like:

[Company1Task1, Company2Task1, Company1Task2, Company3Task1, Company1Task3, ...]

And the Executor will process it sequentially.