Thread Pool in Java Example

In this article, we will take a look at what is the thread pool in java, and what it does?. We will also discuss how to create the thread pool using a few examples.

You will learn
– What is Thread Pool?
– Which option is better – creating a new thread every time vs re-using them?
– Type of Thread Pools?
– Create a thread pool using ThreadPoolExecutor, ScheduledThreadPoolExecutor, and ExecutorService with examples.

What is the thread pool in Java?

When we create a thread in Java, JVM actually creates and maps the Java thread to native OS thread.

Thread Pool in Java
Thread Pool in Java

Once thread finishes its allocated task, it terminates and the native OS thread also reclaimed.

Since OS is responsible for context-switching for threads, you may see performance issues when you are running a lot of threads

Therefore, we should try to avoid the creation of multiple threads (100s of) and focus on reusing them.

Here the thread pool concept comes into the picture.

The thread pool is the collection or pool of the worker threads that can execute allocated tasks asynchronously.

One main advantage of the thread pool is that you reduce the number of threads in your application and effectively reuse the existing one.

Now as we know what is thread pool, let’s try to create a thread pool and executes the jobs using them.

We can use ThreadPoolExecutor or ExecutorService to create a thread pool.

Type of Thread Pool

Java provides four types of thread pools.

  1. Fixed Thread Pool.
  2. Cached Thread Pool.
  3. Scheduled Thread Pool.
  4. Single-Thread Executor.

Fixed Thread Pool using the ThreadPoolExecutor

A fixed thread pool contains the fixed number of threads in the thread pool.

ThreadPoolExecutor provides the implementation of a fixed thread pool.

Introduced in Java 1.5, ThreadPoolExecutor is a child of AbstractExecutorService which further implements the ExecutorService class.

ThreadPoolExecutor contains a pool of threads that can be configured using the Executor factory method.

When a task (runnable/callable) is submitted to execute, ThreadPoolExecutor queue the task in blocking queue and execute them using one of possible thread from the thread pool.

For a better understanding let’s create an example.

ThreadPoolExecutor Example

To create a thread pool, we can use the factory method of the Executor framework.

In the above example, you could notice that we are using the newFixedThreadPool factory method of Executors class.

The newFixedThreadPool method takes accept one parameter that specifies the maximum number of thread available in the thread pool.

newFixedThreadPool method of Executors class
newFixedThreadPool method of Executors class

In the above example have specified that a thread pool of a maximum of 5 threads can be created by the ThreadPoolExecutor.

Once the thread pool of 5 threads created, they will exist in the thread pool until the shutdown() called, and they will execute the submitted tasks.

Therefore, if all threads are busy in executing the submitted task then newly submitted tasks have to wait in the queue until threads are available.

If a thread terminated due to some failure then a new thread will be created to replace terminated thread.

Nevertheless, the maximum number of permitted thread in the thread pool will be 5 (in our case).

You will get below output when you execute the above program.

Cached Thread Pool with ExecutorService

Unlike a fixed-size thread pool that will have a collection of threads, the cached thread pool is different.

The cached thread pool doesn’t maintain any blocking queue to hold the tasks.

The cached thread pool maintains a synchronous queue that can hold just one task.

When all threads are busy in executing the tasks, the cached thread pool creates another thread to run the task.

For example, if you are performing IO intensive operation and 100 more requests come then the cached thread pool can create another 100 threads which are not good.

However, the cached thread pool has the ability to kill a thread that is in an idle state for 60 seconds.

Let’s create the cached thread pool using executors factory method.

Thread Pool with ScheduledThreadPoolExecutor Example

ScheduledThreadPoolExecutor is a specialized class of ThreadPoolExecutor.

This class is useful if you want to create a thread pool that can schedule the jobs after some given delay.

ScheduledThreadPoolExecutor maintains a delay queue to queue the tasks.

The delay queue is a special kind of queue that might not queue the tasks in sequential order.

The task from the delay queue distributed based on when the tasks need to be executed.

In the below example we have created three tasks task1, task2, and task3.

However, task1 will be executed periodically after every 1 second.

Therefore, the delay queue will bring the task1 to the front in every 1 second.

Let’s create an example using ScheduledThreadPoolExecutor.

In the above example, you may notice we are using a newScheduledThreadPool method of the Executors class to create the thread pool of scheduled thread pool executor.

To submit the task that will run periodically, we can use the scheduleWithFixedDelay method of the scheduled thread pool executor class.

The first parameter of the method specifies the task it has to perform periodically.

The second parameter specifies the initial delay.

The third parameter tells the delay after the periodic tasks will trigger periodically.

Let’s discuss another way to create the thread pool using ExecutorService.

Thread Pool using Executor Service

ExecutorService simplifies the execution of tasks asynchronously by using available thread from the thread pool.

The most common way to create an instance of ExecutorService is through the factory class Executors.

For example, if you want to create a pool with 10 threads, you can do it this way:

Conclusion

In this tutorial, we have learned what is thread pool.

We have also learned how to create thread pool using ThreadPoolExecutor, ScheduledThreadPoolExecutor, and ExecutorService with a few examples.

In case if you have some doubts you can ask in the below comment section.

2 thoughts on “Thread Pool in Java Example”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.