Overview
The Thread Pool Design Pattern is a concurrency pattern that maintains a pool of threads to perform tasks, reusing existing threads instead of creating new ones. This helps manage system resources efficiently and improves application performance.
Key Characteristics
- Limits the number of threads created to improve resource utilization.
- Reuses threads for multiple tasks, reducing the overhead of thread creation and destruction.
- Provides a mechanism for queuing tasks when all threads are busy.
Implementation
The following is an example of a Thread Pool implementation in Java:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Task implements Runnable {
private final String name;
public Task(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("Task " + name + " is being executed by " + Thread.currentThread().getName());
try {
Thread.sleep(2000); // Simulate task execution time
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task " + name + " is finished.");
}
}
public class ThreadPoolDemo {
public static void main(String[] args) {
// Create a thread pool with 3 threads
ExecutorService executorService = Executors.newFixedThreadPool(3);
// Submit tasks to the thread pool
for (int i = 1; i <= 5; i++) {
Task task = new Task("Task-" + i);
executorService.submit(task);
}
// Shutdown the thread pool
executorService.shutdown();
}
}
When to Use
- When you have multiple tasks to execute concurrently.
- When creating and destroying threads frequently would lead to performance overhead.
- When you want to limit the number of concurrent threads to avoid resource contention.
Advantages
- Reduces the overhead of thread creation and destruction.
- Efficient use of system resources by limiting the number of active threads.
- Improves application performance by reusing threads for multiple tasks.
Disadvantages
- Requires careful configuration of the thread pool size to balance performance and resource usage.
- May lead to task queuing or delays if all threads are busy and the pool size is insufficient.