Monday, 16 January 2017

What is ExecutorService in Java?

ExecutorService interface represents an asynchronous execution mechanism which is capable of executing tasks in the background. An ExecutorService is thus very similar to a thread pool Task Delegation.


Once the thread has delegated the task to the ExecutorService, the thread continues its own execution independent of the execution of that task.

ThreadPoolExecutor
 is an implementation of the ExecutorService interface. The ThreadPoolExecutor executes the given task (Callable or Runnable) using one of its internally pooled threads.
The thread pool contained inside the ThreadPoolExecutor can contain a varying amount of threads. 

The number of threads in the pool is determined by these variables: 

corePoolSizemaximumPoolSize

If less than corePoolSize threads are created in the thread pool when a task is delegated to the thread pool, then a new thread is created, even if idle threads exist in the pool.

If the internal queue of tasks is full, and corePoolSize threads or more are running, but less than maximumPoolSize threads are running, then a new thread is created to execute the task.

Here is a diagram illustrating the ThreadPoolExecutor principles:



ScheduledExecutorService is an ExecutorService which can schedule tasks to run after a delayor to execute repeatedly with a fixed interval of time in between each execution. Tasks are executed asynchronously by a worker thread, and not by the thread handing the task to the ScheduledExecutorService

No comments:

Post a Comment