Sub topic 12
Tuning ThreadPoolExecutor: Pool Sizes, Queues, and Rejection Policies
So far you have made thread pools with factory methods like Executors.newFixedThreadPool(4). Those methods are handy, but each one picks its settings for you. Behind every one of them is the same class, ThreadPoolExecutor. In this chapter you will build a ThreadPoolExecutor yourself and choose every setting.
Why would you want to? Here are two reasons:
- You can limit how much work waits in line, so your program does not run out of memory.
- You can decide what happens when the pool is too busy to take more work.
The Six Settings of a ThreadPoolExecutor
A constructor is the special method that builds a new object. The most common ThreadPoolExecutor constructor takes six values:
| Setting | What it means |
|---|---|
| `corePoolSize` | The number of threads the pool tries to keep alive, even when they have nothing to do. |
| `maximumPoolSize` | The most threads the pool is allowed to have at once. |
| `keepAliveTime` | How long an extra thread (above the core size) may sit idle before it is stopped. |
| `unit` | The time unit for `keepAliveTime`, such as `TimeUnit.SECONDS`. |
| `workQueue` | The line where tasks wait when every thread is busy. |
| `handler` | The **rejection policy**: the rule for what to do with a task the pool cannot accept. |
A core thread is one of the first corePoolSize threads. An extra thread is any thread beyond that number, up to the maximum.
How the Pool Decides What to Do With a New Task
When you call execute or submit, the pool follows these steps in this order:
- If fewer than
corePoolSizethreads are running, it starts a new thread for the task. - Otherwise, it tries to put the task in the work queue.
- If the queue is full, it starts an extra thread, as long as it has fewer than
maximumPoolSizethreads. - If the pool already has the maximum number of threads and the queue is full, it rejects the task. Rejecting means it hands the task to the rejection policy.
Building a Custom Pool
Here is a pool with 2 core threads, up to 4 threads in total, a queue that holds 100 tasks, and the CallerRunsPolicy rejection policy.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class CustomPoolDemo {
public static void main(String[] args) {
ThreadPoolExecutor pool = new ThreadPoolExecutor(
2,
4,
30, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(100),
new ThreadPoolExecutor.CallerRunsPolicy());
for (int i = 0; i < 10; i++) {
int id = i;
pool.execute(() -> System.out.println("Task " + id + " on " + Thread.currentThread().getName()));
}
pool.shutdown();
}
}Let's walk through it:
2is the core size, and4is the maximum size.30, TimeUnit.SECONDSmeans an extra thread that is idle for 30 seconds gets stopped.new ArrayBlockingQueue<>(100)is a bounded queue, which means it has a fixed capacity. Here it holds at most 100 waiting tasks.CallerRunsPolicyis explained below.
When you run it, you will probably see only pool-1-thread-1 and pool-1-thread-2 in the output. Ten tasks fit easily in a queue of 100, so the pool never needs extra threads. This matches step 2 of the rules.
Choosing a Work Queue
The work queue is a BlockingQueue, a queue that is safe for many threads to use at once. Three kinds are common:
| Queue | Capacity | Effect on the pool |
|---|---|---|
| `ArrayBlockingQueue` | Fixed, set by you | Tasks wait up to that limit. After that, extra threads start, then rejection happens. |
| `LinkedBlockingQueue` (no size given) | Practically unlimited | The queue never fills up, so the pool never grows past the core size and never rejects tasks. |
| `SynchronousQueue` | Zero | Nothing can wait. Each task must go straight to a thread, so the pool grows quickly. |
These choices explain the factory methods you already know:
Executors.newFixedThreadPool(n)uses core sizen, maximum sizen, and an unlimitedLinkedBlockingQueue.Executors.newCachedThreadPool()uses core size 0, a huge maximum (Integer.MAX_VALUE), a 60-second keep-alive time, and aSynchronousQueue.
Rejection Policies
Java gives you four ready-made rejection policies. Each one is a nested class inside ThreadPoolExecutor.
| Policy | What happens to the rejected task |
|---|---|
| `AbortPolicy` (the default) | The pool throws a `RejectedExecutionException`. |
| `CallerRunsPolicy` | The thread that called `execute` runs the task itself. |
| `DiscardPolicy` | The task is silently thrown away. |
| `DiscardOldestPolicy` | The oldest task in the queue is thrown away, and the pool tries again with the new one. |
CallerRunsPolicy is a popular choice. While the calling thread is busy running the task, it cannot submit more tasks. This slows down the producer, the code that creates tasks, until the pool catches up. This slowing effect is called back pressure.
The two discard policies lose work without any message, so use them only when losing a task is truly fine. One example is dropping an old sensor reading when a newer one exists.
Watching the Rules in Action
This next program uses a tiny pool so you can see every step happen. It has 1 core thread, a maximum of 2 threads, and a queue that holds just 1 task. Each task sleeps for half a second, so the threads stay busy.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class RejectionDemo {
public static void main(String[] args) {
ThreadPoolExecutor pool = new ThreadPoolExecutor(
1,
2,
10, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1),
new ThreadPoolExecutor.AbortPolicy());
for (int i = 0; i < 4; i++) {
int id = i;
Runnable task = () -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Finished task " + id);
};
try {
pool.execute(task);
System.out.println("Accepted task " + id
+ " | threads: " + pool.getPoolSize()
+ " | queued: " + pool.getQueue().size());
} catch (RejectedExecutionException e) {
System.out.println("Rejected task " + id);
}
}
pool.shutdown();
}
}The output starts like this:
Accepted task 0 | threads: 1 | queued: 0
Accepted task 1 | threads: 1 | queued: 1
Accepted task 2 | threads: 2 | queued: 1
Rejected task 3Here is why:
- Task 0 starts the one core thread (step 1).
- Task 1 goes into the queue, which is now full (step 2).
- Task 2 cannot be queued, so an extra thread starts (step 3).
- Task 3 arrives when there are 2 threads and a full queue, so it is rejected (step 4).
After about a second, three "Finished" lines appear. Task 3 never runs.
How Many Threads Should You Use?
There is no single right number, but this rule of thumb helps:
- CPU-bound tasks spend their time calculating. More threads than CPU cores will not speed them up. Start with the number of cores, which you get from
Runtime.getRuntime().availableProcessors(). - I/O-bound tasks spend most of their time waiting, for example on files, databases, or the network. A waiting thread uses no CPU, so more threads can help. Start higher and measure.
Always measure with real work. Too few threads leave the CPU idle. Too many waste memory, because each platform thread has its own stack, a block of memory for its method calls.
Common Mistakes
- Setting a maximum with an unlimited queue. With
new LinkedBlockingQueue<>(), the pool never grows past the core size, so your maximum does nothing. - Using a core size of 0 with a bounded queue. The pool still starts one thread when a task arrives with no threads running, but then it waits for the queue to fill before adding more. Work may run on just one thread for a long time.
- Forgetting to handle
RejectedExecutionException. With the default policy, a busy pool throws this exception inside the code that submits tasks. - Forgetting to shut down. A custom pool keeps its core threads alive, and they keep your program running. Use the shutdown pattern from the earlier chapter.
Exercise
A pool has corePoolSize 2, maximumPoolSize 5, and an ArrayBlockingQueue with capacity 3. Every task runs for a long time. You submit 9 tasks quickly. How many threads run, how many tasks wait in the queue, and how many are rejected?
Show answer
Tasks 1 and 2 start the 2 core threads. Tasks 3 to 5 fill the queue (3 tasks). Tasks 6 to 8 start 3 extra threads, bringing the pool to its maximum of 5. Task 9 is rejected. So 5 threads run, 3 tasks wait, and 1 task is rejected.
Exercise
You build a pool with new ThreadPoolExecutor(2, 10, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>()). Under heavy load, why does it never use more than 2 threads?
Show answer
A LinkedBlockingQueue created without a size is practically unlimited, so it never fills. The pool only adds extra threads when the queue is full, so it stays at the core size of 2. To let it grow, use a bounded queue such as new ArrayBlockingQueue<>(50), or raise the core size.
Exercise
Your program reads messages and submits one task per message. Sometimes messages arrive faster than the pool can handle them, and you must not lose any message. Which rejection policy fits, and why?
Show answer
CallerRunsPolicy fits. When the pool and queue are full, the thread that reads messages runs the task itself. That slows down reading, which gives the pool time to catch up, and no task is thrown away. AbortPolicy would throw an exception, and the two discard policies would lose messages.