Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Executor Service with multiple queues

Tags:

People also ask

How will you create multiple pool using Java ExecutorService?

Creating an ExecutornewCachedThreadPool() — An ExecutorService with a thread pool that creates new threads as required but reuses previously created threads as they become available. Executors. newFixedThreadPool(int numThreads) — An ExecutorService that has a thread pool with a fixed number of threads.

How do you run multiple threads concurrently in Java ExecutorService approach?

ExecutorService executor = Executors. newFixedThreadPool(crunchifyThreads); // newFixedThreadPool(): 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.

What is the difference between Executor and ExecutorService?

Executor just executes stuff you give it. ExecutorService adds startup, shutdown, and the ability to wait for and look at the status of jobs you've submitted for execution on top of Executor (which it extends). This is a perfect answer, short and clear.

Is ExecutorService asynchronous?

ExecutorService is a JDK API that simplifies running tasks in asynchronous mode. Generally speaking, ExecutorService automatically provides a pool of threads and an API for assigning tasks to it.


Requirement:

  1. I have messages grouped into different types e.g Type1, Type2 ... Type100.
  2. I want to execute different types of messages in parallel. Let's say in 10 threads, but all the messages of a same type must execute one by one. Execution order does not matter.
  3. Once a thread finish all the messages of TypeX. It should start processing another Type.

I went through the different answers: Most of them suggests executor service to handle multi-threading. Let's say we create executor service like

ExecutorService executorService = Executors.newFixedThreadPool(10);

but once we submit the message using executorService.submit(runnableMessage);

We don't get any control over the assignment of specific Type of message to a particular thread only.

Solution:

creating an array of single threaded executors

ExecutorService[] pools = new ExecutorService[10];

and initially pass the messages of Type1, Type2 ... Type10 then if any executor has finished execution then assign Type11 to it and keep doing it until all Types gets processed.

Is there any better way to do it?

Something like executor service with multiple queues where I can push messages of each type to a different queue?