0
0
JavaConceptBeginner · 3 min read

What is Thread Pool in Java: Explanation and Example

A 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.

java
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
    }
}
Output
Task 1 is running on pool-1-thread-1 Task 2 is running on pool-1-thread-2 Task 3 is running on pool-1-thread-3 Task 1 completed on pool-1-thread-1 Task 4 is running on pool-1-thread-1 Task 2 completed on pool-1-thread-2 Task 5 is running on pool-1-thread-2 Task 3 completed on pool-1-thread-3 Task 4 completed on pool-1-thread-1 Task 5 completed on pool-1-thread-2
🎯

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 ExecutorService interface.
  • Always shut down the pool to free resources when done.

Key Takeaways

A thread pool reuses a fixed number of threads to run multiple tasks efficiently.
It reduces the overhead of creating and destroying threads repeatedly.
Use thread pools for handling many short or frequent tasks in parallel.
Java's ExecutorService makes it easy to create and manage thread pools.
Always shut down the thread pool after use to release resources.