00:00

ThreadPoolExecutor Class in Java: Constructor, Queuing and Hooks

Last updated:

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

ThreadPoolExecutor hierarchyThreadPoolExecutor extends AbstractExecutorService. ScheduledThreadPoolExecutor extends ThreadPoolExecutor. ThreadPoolExecutor uses a RejectedExecutionHandler when it cannot accept a task.«abstract class»AbstractExecutorServicesubmit(…), invokeAll(…), invokeAny(…)«class»ThreadPoolExecutorthis pageexecute(Runnable)setCorePoolSize(int)getPoolSize(), getQueue()beforeExecute(…) «protected»afterExecute(…) «protected»«class»ScheduledThreadPoolExecutorschedule(…)«interface»RejectedExecutionHandlerrejectedExecution(task, pool)handlerextendsuses / createsinterfaceabstract classclass

Swipe sideways to see the whole diagram.

  • AbstractExecutorService (abstract class): Gives ThreadPoolExecutor its submit() and invoke…() 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

Full constructor
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.

ParameterMeaning
corePoolSizeThreads kept alive even when idle (unless core timeout is enabled).
maximumPoolSizeUpper limit on the number of threads.
keepAliveTime, unitHow long threads above the core size may stay idle before they end.
workQueueHolds tasks waiting for a free thread.
threadFactoryCreates new threads, for example to set names or daemon status.
handlerCalled when a task cannot be accepted.

3. How Tasks Are Queued or Rejected

  1. If fewer than corePoolSize threads are running, a new thread is started for the task.
  2. Otherwise the task is put in the work queue.
  3. If the queue is full, a new thread is started, as long as the total stays within maximumPoolSize.
  4. 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.

OrderIntakePool.java
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());
    }
}
Output
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

  1. Every task waits on a CountDownLatch, so no worker becomes free during the experiment.
  2. Orders 1 and 2 start the two core threads. Orders 3 and 4 fill the queue.
  3. Orders 5 and 6 find the queue full, so the pool grows to its maximum of 4 threads.
  4. Order 7 cannot be queued or given a thread, so the default AbortPolicy throws RejectedExecutionException.
  5. After the latch is released, all six accepted tasks complete.

5. Rejection Policies

HandlerBehaviour
AbortPolicyDefault. Throws RejectedExecutionException.
CallerRunsPolicyRuns the task on the submitting thread, which naturally slows producers down.
DiscardPolicySilently drops the task. Use only when losing tasks is acceptable.
DiscardOldestPolicyDrops 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.

TimedPool.java
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
    }
}
Output
before task 1
after  task 1 (ok)
before task 2
after  task 2 (ok)
pool terminated

How the code works

  1. beforeExecute() runs on the worker thread just before each task.
  2. afterExecute() runs after each task; its Throwable argument is non-null only if a task given to execute() threw.
  3. terminated() runs once, when the pool has fully shut down.
  4. The audit list is printed only after awaitTermination(), so every entry is visible to main.

7. Common Mistakes and Best Practices

  • Expecting growth with an unbounded queue. maximumPoolSize has 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 ThreadFactory that names threads after their purpose, which makes thread dumps readable.
  • Exceptions from submit(). They are captured in the Future, so afterExecute() sees null; inspect the Future if you need them.
  • Tuning at runtime. setCorePoolSize() and setMaximumPoolSize() can resize a running pool.

8. Summary

  • ThreadPoolExecutor extends AbstractExecutorService and backs most Executors pools.
  • New threads up to the core size, then the queue, then extra threads up to the maximum, then rejection.
  • AbortPolicy is the default handler; CallerRunsPolicy provides back-pressure.
  • beforeExecute(), afterExecute() and terminated() are hooks for monitoring.

Related Tutorials

9. References