Sub topic 6
Letting a Thread Pool Do the Work: ExecutorService
In earlier chapters you made threads yourself with new Thread(...). That works for one or two jobs. Real programs often have hundreds of small jobs, and creating a new thread for each one is slow and wasteful. Java has a better tool for this.
What Is a Thread Pool?
A thread pool is a group of threads that are created once and then reused. You do not hand work to a specific thread. You give the job to the pool, and any free thread in the pool picks it up.
A task is one piece of work you want done. In Java, a task is often a Runnable, the same interface you used with Thread.
An ExecutorService is the Java interface for a thread pool. You submit tasks to it, and it decides which thread runs each one. Your code describes the work, and the pool takes care of the threads.
When every thread is busy, new tasks wait in a queue, a line where items are handled in arrival order. When a thread finishes a task, it takes the next one from the queue.
Why Use a Pool?
- Less overhead. Making a thread costs time and memory. A pool makes its threads once.
- A limit on threads. A fixed pool never runs more threads than you allow, so a flood of tasks cannot overload the machine.
- Simpler code. You stop calling
startandjoinon each thread by hand.
Making a Pool with the Executors Factory
The Executors class has factory methods, which are static methods that build objects for you. Here are the common ones:
| Method | What you get | Good for |
|---|---|---|
| `Executors.newFixedThreadPool(n)` | Exactly `n` threads | Steady workloads with a known limit |
| `Executors.newSingleThreadExecutor()` | One thread, tasks run in order | Jobs that must not overlap |
| `Executors.newCachedThreadPool()` | Makes threads as needed, reuses idle ones | Many short tasks |
A Worked Example
This program makes a pool of 3 threads and gives it 6 tasks.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class PoolDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 6; i++) {
int id = i;
pool.execute(() -> System.out.println(
"Task " + id + " on " + Thread.currentThread().getName()));
}
pool.shutdown();
}
}Step by step:
newFixedThreadPool(3)builds a pool with three threads.- The loop submits six tasks with
execute. Theexecutemethod takes aRunnableand returns nothing. - The line
int id = i;copies the loop counter. A lambda can only use local variables that never change, andichanges on every pass through the loop. shutdowntells the pool to accept no new tasks. It still finishes the tasks it already has, and then its threads stop.
Here is one possible output:
Task 1 on pool-1-thread-1
Task 3 on pool-1-thread-3
Task 2 on pool-1-thread-2
Task 4 on pool-1-thread-1
Task 5 on pool-1-thread-3
Task 6 on pool-1-thread-2Only three thread names appear, even though six tasks ran. Each thread ran more than one task. The order changes from run to run because the threads run at the same time.
execute vs. submit
An ExecutorService also has a submit method. It accepts the same tasks, and it returns an object that lets you check on the task or get a result back. The next chapter covers that object.
Exercise
You create a pool with Executors.newFixedThreadPool(2) and call execute ten times. How many threads run tasks, and what happens to the tasks that cannot start right away?
Show answer
Only two threads run tasks. The other tasks wait in the pool's queue, and each one starts as soon as one of the two threads finishes its current task.
Exercise
Your program prints every task's output but never exits. What did you most likely forget?
Show answer
You forgot to call shutdown on the ExecutorService. Its threads stay alive waiting for new tasks, which keeps the program running.