Video in progress

How do ThreadPoolExecutor's core, max, queue and rejection settings work together?

When a new task arrives: if there are fewer threads than core, a new thread is started; otherwise it goes into the queue; if the queue is full, new threads are started up to max; if that is full too, the rejection policy applies. It is not "threads up to max first, then the queue", as most people expect.

📖 Answer

This order is the place that trips people up most in interviews:

new ThreadPoolExecutor(
        4,                       // corePoolSize
        20,                      // maximumPoolSize
        60, TimeUnit.SECONDS,    // threads above core die after sitting idle this long
        new LinkedBlockingQueue<>(),   // unbounded!
        new ThreadPoolExecutor.AbortPolicy());

This pool never opens more than 4 threads. The queue is unbounded and never fills up, so max=20 is just decoration. When load grows, it is the queue that grows, not the threads.

For it to work properly, the queue has to be bounded: new ArrayBlockingQueue<>(200). Then 4 threads busy → 200 tasks in the queue → 16 more threads get added → then rejection.

The rejection options:

  • AbortPolicy (the default): RejectedExecutionException;
  • CallerRunsPolicy: the calling thread runs the task itself, which is natural backpressure;
  • DiscardPolicy / DiscardOldestPolicy: drop silently, only for work you can afford to lose.

Choosing the size: for CPU-heavy work roughly the number of cores, for I/O-heavy work more. But confirm the number with a load test and metrics like getQueue().size() and getActiveCount(), not by guessing.