Sub topic 6
Letting a Thread Pool Do the Work: ExecutorService
In the earlier chapters you made each thread yourself with new Thread(...). You started it, joined it, and then it was gone. That works for one or two threads. It gets hard when a program has hundreds of small jobs to run.
This chapter introduces the ExecutorService. It lets you hand over a job and stop thinking about which thread runs it.
The problem with one thread per job
Picture a web server that starts a new thread for every request. Each thread costs something:
- Memory. Every thread gets its own stack. A stack is the memory a thread uses to track the methods it is running.
- Start-up time. Creating a thread and starting it takes work from the operating system.
- No limit. If 10,000 requests arrive at once, you get 10,000 threads. The computer can slow down badly or run out of memory.
Your code also mixes two different jobs. One job is what to do, such as "resize this image." The other is how to run it: making threads, starting them, and cleaning up. The ExecutorService separates the two.
What a thread pool is
A thread pool is a group of threads that are created once and then reused for many tasks. A task is a piece of work you want done, usually written as a Runnable lambda.
A pool has two main parts:
- Worker threads. These are the threads in the pool. Each one takes a task, runs it, and then takes the next one.
- A work queue. A queue is a waiting line. Tasks wait here until a worker is free.
Because the threads are reused, you pay the start-up cost only once. Because the pool has a fixed number of threads, 10,000 tasks do not turn into 10,000 threads. The extra tasks wait in the queue.
ExecutorService and Executors
Java gives you these names in the java.util.concurrent package:
| Name | What it is |
|---|---|
| `Executor` | A small interface with one method, `execute(Runnable)`. It means "run this task somehow." |
| `ExecutorService` | A bigger interface built on `Executor`. It adds ways to get results and to shut the pool down. |
| `Executors` | A helper class (note the "s") with factory methods that build ready-made pools. |
A factory method is a static method that creates an object for you, so you don't call a constructor yourself. You almost always type your variable as ExecutorService and build it with Executors.
Worked example: your first pool
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();
}
}Here is what each part does:
Executors.newFixedThreadPool(3)builds a pool that uses at most 3 worker threads.int id = i;copies the loop number into a new variable. A lambda can only use local variables that never change, andichanges on every loop.pool.execute(...)hands the task to the pool. The method returns right away. It does not wait for the task to run.pool.shutdown()tells the pool that no more tasks are coming. The pool finishes the tasks it already has, and then its threads stop.
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-2Look at the thread names. Only three names appear, even though there were six tasks. This shows that the same threads were reused. The order can be different every time you run it, because the threads run at the same time.
Seeing the queue at work
The next program makes the queue visible. Each task sleeps for half a second, which stands in for slow work such as a network call. The pool has only 2 threads, so the 6 tasks must take turns.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class QueueDemo {
public static void main(String[] args) {
long start = System.currentTimeMillis();
ExecutorService pool = Executors.newFixedThreadPool(2);
for (int i = 1; i <= 6; i++) {
int id = i;
pool.execute(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
long elapsed = System.currentTimeMillis() - start;
System.out.println("Task " + id + " done at about " + elapsed + " ms on "
+ Thread.currentThread().getName());
});
}
pool.shutdown();
System.out.println("All tasks submitted");
}
}Typical output:
All tasks submitted
Task 1 done at about 505 ms on pool-1-thread-1
Task 2 done at about 505 ms on pool-1-thread-2
Task 3 done at about 1006 ms on pool-1-thread-1
Task 4 done at about 1006 ms on pool-1-thread-2
Task 5 done at about 1507 ms on pool-1-thread-1
Task 6 done at about 1507 ms on pool-1-thread-2This output teaches two things:
- "All tasks submitted" prints first. Handing a task to the pool does not wait for it. The main thread moves on at once.
- Tasks finish in pairs. With 2 threads, 2 tasks run at a time and the rest wait in the queue. Six tasks of 500 ms take about 1,500 ms in total, not 500 ms and not 3,000 ms.
The catch block puts the interrupt flag back with Thread.currentThread().interrupt(), as you saw in the chapter on interrupting threads. A Runnable cannot throw InterruptedException, so you must catch it inside the task.
The main factory methods
Executors offers several kinds of pool. These are the ones you will use most:
| Factory method | Threads | Best for |
|---|---|---|
| `newFixedThreadPool(n)` | Exactly up to `n`, kept alive | A steady flow of work where you want a firm limit on threads |
| `newSingleThreadExecutor()` | Exactly 1 | Tasks that must run one at a time, in the order you submit them |
| `newCachedThreadPool()` | As many as needed, idle ones removed after 60 seconds | Many short tasks that come in bursts |
| `newScheduledThreadPool(n)` | Up to `n` | Tasks that run later or repeat (covered in a later chapter) |
| `newVirtualThreadPerTaskExecutor()` | One new virtual thread per task | Java 21 and later, many tasks that wait a lot (covered in the last chapter) |
A single-thread executor keeps order
A single-thread executor is handy when tasks must not overlap. For example, writing lines to one log file must happen one line at a time.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SingleThreadDemo {
public static void main(String[] args) {
ExecutorService writer = Executors.newSingleThreadExecutor();
for (int i = 1; i <= 5; i++) {
int line = i;
writer.execute(() -> System.out.println("Writing line " + line));
}
writer.shutdown();
}
}This always prints lines 1 to 5 in order. There is only one worker, and it takes tasks from the queue in the order they arrived. That is the same as running them one by one, except that the work happens off the main thread.
A cached pool grows and shrinks
A cached pool makes a new thread when every existing thread is busy. When a thread sits idle for 60 seconds, the pool removes it. This makes it fast for short bursts of work. It also has a danger: there is no upper limit. If tasks arrive faster than they finish, the pool keeps adding threads.
execute versus submit
So far you used execute. ExecutorService also has submit. Both hand a task to the pool.
| Method | Accepts | Returns |
|---|---|---|
| `execute(Runnable)` | A `Runnable` | Nothing (`void`) |
| `submit(Runnable)` | A `Runnable` | A `Future` you can use to check on the task |
| `submit(Callable)` | A `Callable`, a task that returns a value | A `Future` that holds the value |
Use execute when you only want the task to run and do not need anything back. Use submit when you want a result or want to know when the task is done. The next chapter explains Callable and Future.
How many threads should a pool have?
There is no single right number, but a simple rule gets you started. It depends on what the tasks spend their time doing.
- CPU-bound tasks spend their time calculating, for example compressing a file. More threads than processor cores will not help, because the cores are already busy. Start with the number of cores.
- I/O-bound tasks spend their time waiting, for example on a database or a web page. While one thread waits, another can run. These pools can be bigger than the number of cores.
You can ask Java how many cores it can use:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SizeDemo {
public static void main(String[] args) {
int cores = Runtime.getRuntime().availableProcessors();
System.out.println("Cores available: " + cores);
ExecutorService pool = Executors.newFixedThreadPool(cores);
pool.execute(() -> System.out.println("Running on " + Thread.currentThread().getName()));
pool.shutdown();
}
}Common mistakes
- Making a new pool for every task. This throws away the main benefit of a pool. Create the pool once, share it, and shut it down when the program is finished with it.
- Forgetting
shutdown. The program seems to hang at the end, because idle pool threads are still waiting for work. - Assuming tasks run in submit order. Only a single-thread executor promises that. In a pool with more than one thread, tasks run side by side and can finish in any order.
- Thinking the pool makes shared data safe. It does not. If two tasks change the same variable, you still need
synchronizedor atomic variables from the previous chapter. - Expecting the fixed pool's queue to have a limit. The queue in
newFixedThreadPoolhas no size limit. Millions of waiting tasks can fill memory. The chapter on tuningThreadPoolExecutorshows how to set a limit.
Exercise
A fixed pool has 4 threads. You submit 12 tasks, and each one takes about 1 second. About how long does it take for all of them to finish, and how many different thread names will appear in the output?
Show answer
About 3 seconds. Four tasks run at a time, so the 12 tasks run in 3 rounds of 1 second each. Only 4 different thread names appear (pool-1-thread-1 to pool-1-thread-4), because the pool reuses the same 4 threads.
Exercise
Your program must append messages to a single file, and the messages must appear in exactly the order they were sent. Which Executors factory method should you use, and why?
Show answer
Executors.newSingleThreadExecutor(). It has one worker thread that takes tasks from the queue in the order they were submitted, so writes never overlap and stay in order.
Exercise
A student writes a program that submits tasks to Executors.newFixedThreadPool(2). All the tasks print their output, but the program never exits. What is the most likely cause, and how do you fix it?
Show answer
The student never called pool.shutdown(). The pool's two threads stay alive and keep waiting for new tasks, which keeps the program running. Calling pool.shutdown() after the last task is submitted lets the threads finish their work and stop.