A thread pool in Java is a mechanism to manage a group of reusable threads that can execute tasks concurrently. Instead of creating a new thread every time a task needs to run—which is expensive in terms of memory and CPU—threads are reused from the pool. This improves performance and resource management.
Here’s a detailed breakdown:
1. Why Use a Thread Pool
- Creating threads is costly in Java.
- Too many threads can lead to excessive context switching.
- Thread pools allow you to limit the number of concurrent threads.
- They reuse threads, reducing overhead.
2. Java Thread Pool API
Java provides the Executor
framework in java.util.concurrent
:
Executor
– basic interface to execute tasks.ExecutorService
– more advanced interface that provides methods for task management (submit()
,shutdown()
, etc.).ScheduledExecutorService
– for scheduling tasks with delays or at fixed intervals.
3. Creating Thread Pools
Java provides the Executors
factory class:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
// Create a thread pool with 3 threads
ExecutorService executor = Executors.newFixedThreadPool(3);
// Submit tasks
for (int i = 1; i <= 5; i++) {
int taskId = i;
executor.submit(() -> {
System.out.println("Task " + taskId + " is running by " + Thread.currentThread().getName());
try {
Thread.sleep(2000); // Simulate work
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
// Shutdown the executor
executor.shutdown();
}
}
Explanation:
newFixedThreadPool(3)
– creates a pool of 3 threads.submit()
– submits a task for execution.shutdown()
– stops accepting new tasks and shuts down after completing running tasks.
4. Types of Thread Pools
Type | Description |
---|---|
newFixedThreadPool(n) | Fixed number of threads. Extra tasks wait in a queue. |
newCachedThreadPool() | Creates threads as needed, reuses idle threads. Good for many short-lived tasks. |
newSingleThreadExecutor() | Only one thread. Tasks execute sequentially. |
newScheduledThreadPool(n) | Executes tasks after a delay or periodically. |
5. Key Methods of ExecutorService
submit(Runnable/Callable)
– submit a task.invokeAll()
– submit a collection of tasks and wait for all to complete.shutdown()
– graceful shutdown.shutdownNow()
– immediate shutdown, attempts to stop running tasks.
6. Benefits
- Performance: Reduces overhead of creating threads repeatedly.
- Resource management: Limits the number of concurrent threads.
- Task management: Provides better control over task execution.