What is Thread Pool in Java: Explanation and Example
thread pool in Java is a collection of pre-created threads that are reused to execute multiple tasks, improving performance by avoiding the overhead of creating new threads each time. It manages a fixed number of threads to handle tasks efficiently and safely.How It Works
Imagine you have a small team of workers ready to do jobs. Instead of hiring a new worker for every single task, you keep a fixed team and assign tasks to them as they come. This is how a thread pool works in Java.
When a program needs to run many tasks, creating a new thread for each task can be slow and use a lot of resources. A thread pool creates a set number of threads ahead of time and keeps them ready. When a task arrives, it assigns the task to one of these threads. Once the thread finishes, it goes back to the pool to wait for the next task.
This approach saves time and system resources, making programs faster and more efficient, especially when handling many short tasks.
Example
This example shows how to create a thread pool with 3 threads and submit 5 tasks to it. Each task prints a message and sleeps for a short time.
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolExample { public static void main(String[] args) { ExecutorService pool = Executors.newFixedThreadPool(3); // Create a pool with 3 threads for (int i = 1; i <= 5; i++) { int taskNumber = i; pool.submit(() -> { System.out.println("Task " + taskNumber + " is running on " + Thread.currentThread().getName()); try { Thread.sleep(1000); // Simulate work } catch (InterruptedException e) { Thread.currentThread().interrupt(); } System.out.println("Task " + taskNumber + " completed on " + Thread.currentThread().getName()); }); } pool.shutdown(); // Stop accepting new tasks and finish existing ones } }
When to Use
Use a thread pool when your program needs to run many tasks that can be done in parallel, especially if tasks are short or frequent. It helps avoid the cost of creating and destroying threads repeatedly.
Common real-world uses include web servers handling many user requests, background jobs like sending emails, or processing data in batches. Thread pools improve performance and resource management in these cases.
Key Points
- A thread pool manages a fixed number of reusable threads.
- It improves performance by reducing thread creation overhead.
- Java provides thread pools via the
ExecutorServiceinterface. - Always shut down the pool to free resources when done.