ExecutorService is a JDK API that simplifies running tasks in asynchronous mode. It provides a pool of threads and an API for assigning tasks to it. The executor framework is an implementation of the Producer-Consumer pattern. The java.util.concurrent.Executors class provides a set of methods for creating ThreadPools of worker threads. In this article, we will be looking at types of executors.
Types of executor
- Single thread Executor
The SingleThreadExecutor is a special type of executor that has only a single thread. It is used when we need to execute tasks in sequential order.
ExecutorService executor = Executors.newSingleThreadExecutor()
- Fixed thread pool
FixedThreadPool is another special type of executor that is a thread pool having a fixed number of threads. By this executor, the submitted task is executed by the n thread.
The tasks are then stored in LinkedBlockingQueue until previous tasks are not completed.
ExecutorService executor = Executors.newFixedThreadPool(4);
- Cached thread pool
The CachedThreadPool is a special type of thread pool that is used to execute short-lived parallel tasks. The cached thread pool doesn't have a fixed number of threads. When a new task comes at a time and all the threads are busy executing some other tasks, a new thread is created by the pool and added to the executor.
ExecutorService executor = Executors.newCachedThreadPool();
- Scheduled executor service
The ScheduledExecutorService interface runs tasks after some predefined delay and/or periodically.
ScheduledExecutorService scheduledExecService = Executors.newScheduledThreadPool(1);
The scheduleAtFixedRate and scheduleWithFixedDelay are the two methods that are used to schedule the task in ScheduledExecutor.
The scheduleAtFixedRate method executes the task with a fixed interval when the previous task ended.
The scheduleWithFixedDelay method starts the delay count after the current task is complete.
The main difference between these two methods is their interpretation of the delay between successive executions of a scheduled job.
scheduledExecService.scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
scheduledExecService.scheduleWithFixedDelay(Runnable command, long initialDelay, long period, TimeUnit unit)
The best use case for ExecutorService is the processing of independent tasks, such as transactions or requests according to the scheme “one thread for one task” in Oracle’s documentation, fork/join was designed to speed up work that can be broken into smaller pieces recursively.
That's all for today, Happy Coding!..