Java Concurrency: Thread Pool with Example

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 Pool

In 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 Pool

Creating 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.


ThreadPoolExecutor

ThreadPoolExecutor 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 Executors

1. 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.


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

 class Task implements Runnable {

 private String threadName ;
 
 public Task(String threadName) {  
  this.threadName =  threadName;  
 }
 
 public void run() {
  try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {   
   e.printStackTrace();
  }
  System.out.println(Thread.currentThread().getName()+" "
    + Thread.currentThread().getId());
 }
 
 public String getName() {
  return threadName;
 }
 
 public void setName(String threadName) {
  this.threadName = threadName;
 } 
 
}

 public class ThreadPoolExample {
 
 public static void main(String args[]) {
  ExecutorService service = Executors.newFixedThreadPool(2);
  for (int i=1; i<=4 ; i++) {
   Task task = new Task("Task"+ i);
   System.out.println("Started: "+task.getName());
   service.execute(task);
  }
  service.shutdown();
 }
 
}

Output:

Started: Task1
Started: Task2
Started: Task3
Started: Task4
pool-1-thread-2 10
pool-1-thread-1 9
pool-1-thread-1 9
pool-1-thread-2 10


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.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry