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.
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.
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.
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:
Type1, Type2 ... Type100
.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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With