What is thread pool in Java? Explain with a scenario and code.

(Last Updated On: February 26, 2019)

Answer includes thread pool in java with concept and one simple scenario example and program, where thread pool can be used.

Answer: Thread pool is collection of multiple threads that is used to performed large number of tasks simultaneously. Tried to include multiple scenarios for better understating and answering the concept with one scenario is enough in the interview. However, there is no harm placing all scenarios quickly as an example you know.

Before answering it technically, let’s consider a scenario and find best solution for it.

Let’s say we have 1000 bags in room and want to shift all bags into another room, then what would you do?

Hire one person and shift bags one by one to other room – Very time consuming

Hire 1000 person (call – person pool) and shift all 1000 bags at once – extremely fast processing, but, very costly.

Hire 10 peoples and start shifting simultaneously. Whoever completes his task will pick another bag and start shifting and other people will do the same – For better solution.

So best solution is to create a pool of some person and perform large number of tasks.

 

So, thread pool concept is similar. Create a Thread pool with some worker threads (you have to decide depending upon the tasks). Push all tasks into a queue. All threads from pool will start pulling a task from queue simultaneously and process it. Once a thread completes its task, it should pick next one from the queue. This is the concept of thread pool. Isn’t it simple?

Another problem statement we take as

Let’s say we have 1000 of large files in a folder and a program need to process each file. As a solution, we can create a pool of some worker threads, say 9 workers called a thread pool and all 1000 tasks (processing files) can be pushed into a queue. Now, from the pool, 9 worker threads can pick a task simultaneously from the queue and process it. Whoever completes his task, can pick up the next task from the queue and complete it.

Recommended: Read how to create thread using Runnable interface and thread class in java

Thread pool java program example:

This is simple program example to create a thread pool and perform large task with code comments.

In this thread pool in java program, a thread pool of 5 worker threads will be created and 20 tasks will be pushed into the queue from where 5 threads will start processing each task simultaneously.

 

/*----------------------------------------
 * Thread pool in java program example.
 * */

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

/*----------------------------------------
 * Create a task class and implement runnable interface
 * and Override Run() method.
 * 
 * Runnable is implemented in Task so worker threads
 * can call Run() method of task implicitly
 * */

class Task implements Runnable {
	String taskName;

	public Task(String name) {
		super();
		this.taskName = name;
	}

	@Override
	// All workers of the thread pool will perform
	// printing task
	public void run() {

		print(this.taskName);

	}

	// Thread.currentThread().getName() will give
	// current thread name which is performing task.
	public void print(String task) {

		System.out.println(Thread.currentThread().getName() + " Performed task " + task);
	}

}

/*----------------------------------------
 * Thread pool - Test class
 * 
 * New thread pool of 5 work will be created
 * New 20 task object will be created and 
 * will be push to the queue by executer
 * */

public class ThreadPool {

	public static void main(String[] args) {
		// Create thread pool of 5 workers thread

		ExecutorService executor = Executors.newFixedThreadPool(5);

		// Create 20 tasks that will be push into
		// the thread pool queue and
		// will be executed by 5 threads reside in the threadPool.

		for (int i = 1; i <= 20; i++) { // Create 20 Tasks objects Runnable task = new Task(" Task" + i); /* * From java doc => execute(): Executes the given task at some time in the
			 * future. The task may execute in a new thread, in a pooled thread, or in the
			 * calling thread, at the discretion of the Executor implementation.
			 */

			executor.execute(task);

		}
		/*
		 * shutDown():
		 * 
		 * Initiates an orderly shutdown in which previously submitted tasks are
		 * executed, but no new tasks will be accepted. *
		 * 
		 * shutdown() method method does not wait for previously submitted tasks to
		 * complete execution. Use awaitTermination to do that.
		 * 
		 */
		executor.shutdown();// will not accept new task

		// Terminate threads
		try {
			executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
		} catch (InterruptedException e) {

			e.printStackTrace();
		}
		System.out.println("Thread works are completed");

	}

}

Output:
pool-1-thread-1 Performed task Task1
pool-1-thread-1 Performed task Task6
pool-1-thread-1 Performed task Task7
pool-1-thread-1 Performed task Task8
pool-1-thread-1 Performed task Task9
pool-1-thread-1 Performed task Task10
pool-1-thread-1 Performed task Task11
pool-1-thread-1 Performed task Task12
pool-1-thread-1 Performed task Task13
pool-1-thread-1 Performed task Task14
pool-1-thread-1 Performed task Task15
pool-1-thread-1 Performed task Task16
pool-1-thread-1 Performed task Task17
pool-1-thread-1 Performed task Task18
pool-1-thread-1 Performed task Task19
pool-1-thread-1 Performed task Task20
pool-1-thread-3 Performed task Task3
pool-1-thread-2 Performed task Task2
pool-1-thread-5 Performed task Task5
pool-1-thread-4 Performed task Task4
Thread works are completed

NOTE: On multiple executions of the program, output may vary depending upon the time slice given to threads by CPU.