In this Java Concurrency tutorial, I will be sharing what is a Thread Pool, why do we need Thread Pool, and what are the different kinds of thread pools via executors provided by Java.
What is a Thread PoolIn simple words, Thread Pool is a group of worker threads. Worker threads are waiting for the task( or job). It can be reused many times.
Why do we need Thread PoolCreating a new thread in java is an expensive operation since it requires an Operating System to provide resources needed for the thread. In a large-scale application, there will be a significant memory management overhead for allocating and deallocating many thread objects. Using worker threads in the application minimizes the overhead due to thread creation. As a result, we use Thread Pool for large-scale operations.
Read Also: Multithreading Interview Questions and Answers
Where does this Thread Pool concept is implemented?While designing web servers and application servers we can use the thread pool concept. When any DB connection is required it will check in the connection pool to get the DB connection.
ThreadPoolExecutorThreadPoolExecutor class implements Executor and ExecutorService interface. Task creation and its execution are separated by ThreadPoolExecutor. You only need to implement the Runnable objects and execute them at the executor. ThreadPoolExecutor takes care of instantiation, running, and execution with necessary threads.
How to Create Different Types of ThreadPool Executors1. Cached Thread Pool Executor: According to Java docs, Creates a thread pool that creates new threads as required but will reuse previously constructed threads when they are available.
2. Fixed Thread Pool Executor: Creates a thread pool that execute any number of tasks by reusing a fixed number of threads. It uses an unbounded queue for e.g LinkedBlockingQueue. Suppose if all threads are actively executing the given tasks and we submit additional tasks for execution, then they will wait in the queue until a thread is available.
3. Single Thread Pool Executor: As the name suggests, it will create a single thread to execute all of the given tasks.
4. Scheduled Thread Pool Executor: According to Java docs, create a thread pool that can schedule commands to execute periodically or to run after a given delay.
5. Work Stealing Thread Pool Executor: Using the number of available processors it creates a work-stealing thread pool to support the given parallelism level.
ThreadPool Example:Below is the example of ThreadPool class.
From the above example you can see that only 2 threads are executing the given tasks as we have kept the size of the newFixedThreadPool 2.
That's all for the day, please mention in comments in case you have any questions related to the Thread Pool in java with examples.