Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to create multiple executor service per application java

Tags:

java

When is it a good idea to create more than one executor service per run of a program/application? Why would you do it, instead of just starting up executors.newcachedthreadpool() at the beginning and submitting all callables to it.

like image 518
Sam Adamsh Avatar asked Sep 16 '12 22:09

Sam Adamsh


People also ask

What are the advantages of using ExecutorService instead of creating threads directly?

Below are some benefits: Executor service manage thread in asynchronous way. Use Future callable to get the return result after thread completion. Manage allocation of work to free thread and resale completed work from thread for assigning new work automatically.

Why do we need Executor service in Java?

The ExecutorService helps in maintaining a pool of threads and assigns them tasks. It also provides the facility to queue up tasks until there is a free thread available if the number of tasks is more than the threads available.

Can we limit number of tasks in Executor service?

If there are too many jobs queued up, you can use a fixed size BlockingQueue in the ExecutorService to limit the number of items that can be queued up. Then when you try to queue a new task, the operation will block until there is room in the queue.

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.


1 Answers

  • You might need different flavours (say a fixed thread pool or a scheduled executor)
  • Encapsulation: if a specific class needs to run things through an executor, it makes sense that this class be responsible to decide its execution policy, which is an implementation detail
  • Specialisation - corollary of the previous point:
    • some tasks need many threads (typically network tasks)
    • while others only need a few (CPU-bound task)
    • and some should only use one (if you read/write on your local hard drive for example)
  • There certainly are situations where you want to pass an executor to an object because you want the calling code to control how some tasks will be executed

Bottom line, I can't think of a reason why, for a sufficiently large project, you would want to just use one thread pool for your whole program.

like image 123
assylias Avatar answered Oct 10 '22 13:10

assylias