Thread Pools

Thread pools in Java are a way to manage multiple threads efficiently by reusing a fixed number of threads to execute tasks. This helps in managing system resources better and can lead to performance improvements, especially in applications where you have many short-lived tasks.

Why Use Thread Pools?

  1. Resource Management: Creating a new thread for every task can be expensive. A thread pool reuses a limited number of threads, thus saving resources.
  2. Task Management: By using thread pools, you can control the number of threads executing concurrently, preventing resource exhaustion.
  3. Performance: Reusing threads can reduce the overhead of thread creation and destruction, leading to better performance.

Creating Thread Pools

Java provides the Executor framework to manage threads. The most common interface used is ExecutorService.

Common Methods to Create Thread Pools:

  1. Fixed Thread Pool
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(int nThreads);

Creates a thread pool with a fixed number of threads.
If a thread terminates due to failure during execution, a new one will take its place if needed.Code language: JavaScript (javascript)

     2. Cached Thread Pool

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

Creates a thread pool that creates new threads as needed but will reuse previously constructed 
threads when they are available.
Threads that have not been used for 60 seconds are terminated and removed from the pool.Code language: JavaScript (javascript)

    3. Single Thread Executor

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();

Creates a thread pool with only one thread.
Tasks are executed sequentially.Code language: JavaScript (javascript)

     4. Scheduled Thread Pool

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(int corePoolSize);
Supports executing tasks periodically or after a delay.

Using Thread Pools

To use a thread pool, you submit tasks to it. The tasks are usually instances of Runnable or Callable.

Using Runnable:

ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
    executorService.execute(new RunnableTask());
}
executorService.shutdown();Code language: JavaScript (javascript)

Managing Thread Pools

Shutting Down:

  • shutdown(): Initiates an orderly shutdown where previously submitted tasks are executed, but no new tasks will be accepted.
  • shutdownNow(): Attempts to stop all actively executing tasks and halts the processing of waiting tasks.

Monitoring and Managing:

  • awaitTermination(long timeout, TimeUnit unit): Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

Program Implementation

A complete example using a fixed thread pool with 5 threads

//ThreadPoolDemo.java
import java.util.concurrent.*;
public class ThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            int taskId = i;
            executorService.execute(() -> {
                System.out.println("Task " + taskId + " is running on " + Thread.currentThread().getName());
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Task " + taskId + " completed on " + Thread.currentThread().getName());
            });
        }
        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException ex) {
            executorService.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}

/*
C:\>javac ThreadPoolDemo.java

C:\>java ThreadPoolDemo
Task 1 is running on pool-1-thread-2
Task 4 is running on pool-1-thread-5
Task 3 is running on pool-1-thread-4
Task 0 is running on pool-1-thread-1
Task 2 is running on pool-1-thread-3
Task 1 completed on pool-1-thread-2
Task 5 is running on pool-1-thread-2
Task 2 completed on pool-1-thread-3
Task 3 completed on pool-1-thread-4
Task 0 completed on pool-1-thread-1
Task 8 is running on pool-1-thread-1
Task 7 is running on pool-1-thread-4
Task 6 is running on pool-1-thread-3
Task 4 completed on pool-1-thread-5
Task 9 is running on pool-1-thread-5
Task 8 completed on pool-1-thread-1
Task 6 completed on pool-1-thread-3
Task 7 completed on pool-1-thread-4
Task 5 completed on pool-1-thread-2
Task 9 completed on pool-1-thread-5

C:\>java ThreadPoolDemo
Task 3 is running on pool-1-thread-4
Task 1 is running on pool-1-thread-2
Task 4 is running on pool-1-thread-5
Task 0 is running on pool-1-thread-1
Task 2 is running on pool-1-thread-3
Task 3 completed on pool-1-thread-4
Task 4 completed on pool-1-thread-5
Task 6 is running on pool-1-thread-5
Task 5 is running on pool-1-thread-4
Task 0 completed on pool-1-thread-1
Task 7 is running on pool-1-thread-1
Task 2 completed on pool-1-thread-3
Task 1 completed on pool-1-thread-2
Task 8 is running on pool-1-thread-3
Task 9 is running on pool-1-thread-2
Task 5 completed on pool-1-thread-4
Task 6 completed on pool-1-thread-5
Task 7 completed on pool-1-thread-1
Task 8 completed on pool-1-thread-3
Task 9 completed on pool-1-thread-2

C:\>java ThreadPoolDemo
Task 1 is running on pool-1-thread-2
Task 2 is running on pool-1-thread-3
Task 4 is running on pool-1-thread-5
Task 0 is running on pool-1-thread-1
Task 3 is running on pool-1-thread-4
Task 4 completed on pool-1-thread-5
Task 0 completed on pool-1-thread-1
Task 1 completed on pool-1-thread-2
Task 6 is running on pool-1-thread-1
Task 5 is running on pool-1-thread-5
Task 2 completed on pool-1-thread-3
Task 7 is running on pool-1-thread-2
Task 8 is running on pool-1-thread-3
Task 3 completed on pool-1-thread-4
Task 9 is running on pool-1-thread-4
Task 5 completed on pool-1-thread-5
Task 6 completed on pool-1-thread-1
Task 7 completed on pool-1-thread-2
Task 8 completed on pool-1-thread-3
Task 9 completed on pool-1-thread-4

*/

Thread pools in Java provide a powerful mechanism to handle multiple tasks concurrently while managing system resources efficiently. By using the ExecutorService and its various implementations, you can control the execution of tasks in a robust and scalable way.

Scroll to Top