ThreadPoolExecutor Class in Java: Constructor, Queuing and Hooks
ThreadPoolExecutor is the JDK's general-purpose thread pool. Most of the pools created by the Executors factory methods are instances of it, and creating it directly gives you full control over threads, the work queue and what happens when the pool is overloaded.
This tutorial focuses on the class itself: its constructor parameters, the exact rule it uses to queue or reject tasks, and its extension hooks. For sizing advice, see Thread Pool in Java.
1. ThreadPoolExecutor Hierarchy
Swipe sideways to see the whole diagram.
AbstractExecutorService(abstract class): Gives ThreadPoolExecutor itssubmit()andinvoke…()methods.ScheduledThreadPoolExecutor(class): A subclass that adds delayed and periodic execution.RejectedExecutionHandler(interface): Decides what happens to a task the pool cannot accept.
2. Constructor Details
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
Three shorter overloads omit the thread factory, the handler, or both; they then use Executors.defaultThreadFactory() and AbortPolicy.
| Parameter | Meaning |
|---|---|
corePoolSize | Threads kept alive even when idle (unless core timeout is enabled). |
maximumPoolSize | Upper limit on the number of threads. |
keepAliveTime, unit | How long threads above the core size may stay idle before they end. |
workQueue | Holds tasks waiting for a free thread. |
threadFactory | Creates new threads, for example to set names or daemon status. |
handler | Called when a task cannot be accepted. |
3. How Tasks Are Queued or Rejected
- If fewer than corePoolSize threads are running, a new thread is started for the task.
- Otherwise the task is put in the work queue.
- If the queue is full, a new thread is started, as long as the total stays within maximumPoolSize.
- If that is not possible, the task is rejected and the handler is called.
The order matters: extra threads above the core size are created only when the queue is full. With an unbounded queue, such as the LinkedBlockingQueue used by Executors.newFixedThreadPool(), the pool never grows beyond its core size.
4. Example: Watching a Bounded Pool Fill Up
An order-intake service uses 2 core threads, at most 4 threads, and a queue of 2. Seven orders arrive while every worker is busy.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class OrderIntakePool {
public static void main(String[] args) throws InterruptedException {
CountDownLatch release = new CountDownLatch(1);
ThreadPoolExecutor pool = new ThreadPoolExecutor(
2, // corePoolSize
4, // maximumPoolSize
30, TimeUnit.SECONDS, // keep-alive for threads above core
new ArrayBlockingQueue<>(2)); // bounded work queue (capacity 2)
for (int order = 1; order <= 7; order++) {
try {
pool.execute(() -> {
try {
release.await(); // keep every worker busy
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
System.out.printf("order %d accepted -> threads=%d, queued=%d%n",
order, pool.getPoolSize(), pool.getQueue().size());
} catch (RejectedExecutionException e) {
System.out.printf("order %d REJECTED (pool and queue are full)%n", order);
}
}
release.countDown();
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
System.out.println("Completed tasks: " + pool.getCompletedTaskCount()
+ ", largest pool size: " + pool.getLargestPoolSize());
}
}
order 1 accepted -> threads=1, queued=0 order 2 accepted -> threads=2, queued=0 order 3 accepted -> threads=2, queued=1 order 4 accepted -> threads=2, queued=2 order 5 accepted -> threads=3, queued=2 order 6 accepted -> threads=4, queued=2 order 7 REJECTED (pool and queue are full) Completed tasks: 6, largest pool size: 4
How the code works
- Every task waits on a
CountDownLatch, so no worker becomes free during the experiment. - Orders 1 and 2 start the two core threads. Orders 3 and 4 fill the queue.
- Orders 5 and 6 find the queue full, so the pool grows to its maximum of 4 threads.
- Order 7 cannot be queued or given a thread, so the default
AbortPolicythrowsRejectedExecutionException. - After the latch is released, all six accepted tasks complete.
5. Rejection Policies
| Handler | Behaviour |
|---|---|
AbortPolicy | Default. Throws RejectedExecutionException. |
CallerRunsPolicy | Runs the task on the submitting thread, which naturally slows producers down. |
DiscardPolicy | Silently drops the task. Use only when losing tasks is acceptable. |
DiscardOldestPolicy | Drops the oldest queued task and retries. Rarely the right choice. |
6. Example: Hook Methods
ThreadPoolExecutor has three protected hooks: beforeExecute(), afterExecute() and terminated(). Subclasses override them for logging, metrics or context setup.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
// Uses the beforeExecute / afterExecute / terminated hooks to audit a pool
public class TimedPool extends ThreadPoolExecutor {
private final List<String> audit = new ArrayList<>();
private int started;
TimedPool() {
super(1, 1, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
}
@Override
protected void beforeExecute(Thread worker, Runnable task) {
super.beforeExecute(worker, task);
audit.add("before task " + (++started));
}
@Override
protected void afterExecute(Runnable task, Throwable failure) {
super.afterExecute(task, failure);
audit.add("after task " + started + (failure == null ? " (ok)" : " (failed)"));
}
@Override
protected void terminated() {
super.terminated();
audit.add("pool terminated");
}
public static void main(String[] args) throws InterruptedException {
TimedPool pool = new TimedPool();
pool.execute(() -> { /* compress log file */ });
pool.execute(() -> { /* upload to archive */ });
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
pool.audit.forEach(System.out::println); // safe: the pool has terminated
}
}
before task 1 after task 1 (ok) before task 2 after task 2 (ok) pool terminated
How the code works
beforeExecute()runs on the worker thread just before each task.afterExecute()runs after each task; itsThrowableargument is non-null only if a task given toexecute()threw.terminated()runs once, when the pool has fully shut down.- The audit list is printed only after
awaitTermination(), so every entry is visible tomain.
7. Common Mistakes and Best Practices
- Expecting growth with an unbounded queue.
maximumPoolSizehas no effect while the queue still accepts tasks. - Unbounded queues under heavy load. They can grow until memory runs out; prefer a bounded queue plus a deliberate rejection policy.
- Unnamed threads. Pass a
ThreadFactorythat names threads after their purpose, which makes thread dumps readable. - Exceptions from
submit(). They are captured in the Future, soafterExecute()seesnull; inspect the Future if you need them. - Tuning at runtime.
setCorePoolSize()andsetMaximumPoolSize()can resize a running pool.
8. Summary
ThreadPoolExecutorextendsAbstractExecutorServiceand backs mostExecutorspools.- New threads up to the core size, then the queue, then extra threads up to the maximum, then rejection.
AbortPolicyis the default handler;CallerRunsPolicyprovides back-pressure.beforeExecute(),afterExecute()andterminated()are hooks for monitoring.
Related Tutorials
9. References
Frequently Asked Questions (FAQ)
Q1. When does ThreadPoolExecutor create more threads than corePoolSize?
Only when the work queue is full. Below the core size a new thread is always created; at or above it, tasks are queued first, and extra threads up to maximumPoolSize are created only when the queue cannot accept the task.
Q2. What is the default rejection policy?
ThreadPoolExecutor.AbortPolicy. It throws RejectedExecutionException when a task cannot be accepted.
Q3. What does keepAliveTime control?
How long threads above the core size may stay idle before they terminate. If you call allowCoreThreadTimeOut(true), the same timeout also applies to core threads.
Q4. Is newFixedThreadPool a ThreadPoolExecutor?
Yes. Executors.newFixedThreadPool(n) returns a ThreadPoolExecutor with core and maximum size n and an unbounded LinkedBlockingQueue.
Q5. How can I monitor a ThreadPoolExecutor?
Use methods such as getPoolSize(), getActiveCount(), getQueue().size(), getCompletedTaskCount() and getLargestPoolSize(), or override the beforeExecute() and afterExecute() hooks.